cannot import electron in react componment for ipcRenderer

Viewed 525

So I am trying to import the ipcRenderer into a react component to communicate with the electron side. The issue is I cannot import electron. I tried

import { ipcRenderer } from 'electron/renderer'

returns module electron/renderer not found

import { ipcRenderer } from 'electron'

returns fs.existsSync is not a function

const renderer = require('electron');

returns fs.existsSync is not a function

const renderer = require('electron').ipcRenderer;

returns fs.existsSync is not a function

const renderer = window.require('electron');

returns window.require is not a function

I do not know what to do anymore, I have tried everything

1 Answers

I got it! using electron-react-bolierplate they prepared a custom preload.js script that exposes three functions to the rendered components: myPing: (Just a demo, send a ping message to the console) and exposes the on and once ipcRenderer methods

import { Component } from 'react';
...
...
    class Hello extends Component {
      componentDidMount() {
        console.log('Mounted!', 'Window', window, 'electronApi', window.electron, 'ipcRenderer', window.electron.ipcRenderer);
    
        window.electron.ipcRenderer.on('ipc-example', (arg) => {
          // eslint-disable-next-line no-console
          console.log(arg);
        });
    
        window.electron.ipcRenderer.myPing();
      }
    
      render() {
        return (
          <div>
    ...
    ...
Related