Calling the Electron ipcRenderer method in a React component

Create a preload.js file:

jsx
window.ipcRenderer = require('electron').ipcRenderer;

On main.js:

jsx
// Create the browser window.
mainWindow = new BrowserWindow({
    alwaysOnTop: true,
    frame: false,
    fullscreenable: false,
    transparent: true,
    titleBarStyle: 'customButtonsOnHover',
    show: false,
    width: 300, 
    height: 350,
    webPreferences: {
        nodeIntegration: true,
        preload: __dirname + '/preload.js'
    }
});

// Blur window when close o loses focus
mainWindow.webContents.on('did-finish-load', () => mainWindow.webContents.send('ping', '🤘') );

mainWindow variable on this file will preload the preload.js file. Now the React component can call the window.ipcRenderer method.

On app.js:

jsx
import React, { useEffect, useState } from 'react';
import './App.css';

function App() {
    
    useEffect( () => {
        
        window.ipcRenderer.on('ping', (event, message) => { 
            console.log(message) 
        });
                
    }, []);
            
    return (
    <div className = 'App'></div>
    );
}

export default App;

After running the app from the command line, the window generated by the React process will throw an error ('ipcRenderer is undefined'). Ignore it. The window generated by the Electron process (main app) will work fine. 😅

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.