Tips on Using React with Electron
Following this guide to start off with a light boilerplate: https://medium.com/@impaachu/how-to-build-a-react-based-electron-app-d0f27413f17f
This boilerplate is easy to work with and utilizes create-react-app to start the project. So those familiar with create-react-app should be at home with that guide. However, there are some issues that you may run into while doing various things in the project.
One of the first things is using node packages in your react components. A good way to accomplish this is to do this:
In the electron.js
file in the public folder make sure that your browser window object has a preload file:
mainWindow = new BrowserWindow({
width: 1100,
height: 730,
'minWidth': 500,
'minHeight': 500,
webPreferences: {
nodeIntegration: true,
preload: __dirname + '/preload.js'
},
frame: isDev
});
In your preload.js
file add the node packages to the window object like so:
window.electron = window.require('electron');
window.fs = window.require('fs');
window.path = window.require('path');
This is a potential use case in a component to make a custom window frame:
import React from "react";
import Logo from "../../resources/logo128x128.png"
const remote = window.electron.remote;
const WindowFrame = () => {
const app = remote.getCurrentWindow();
const minimize = () => {
app.minimize();
};
const toggleMaximize = () => {
app.isMaximized() ? app.unmaximize() : app.maximize();
};
const exit = () => {
app.close();
};
return (
<div className="frame">
<img className="frameImage" src={Logo} alt=""/>
<span className="frameTitle">Test Frame Title</span>
<button
className="fas fa-times frameButton exitButton"
onClick={() => exit()}
/>
<button
className="far fa-square frameButton"
onClick={() => toggleMaximize()}
/>
<button className="fas fa-minus frameButton" onClick={() => minimize()} />
</div>
);
};
export default WindowFrame;
Another problem you may run across is calling web API’s in development mode. This was a fairly simple solution that required a small change to the electron.js
file.
We just check if we are in development mode and if we are we disable webSecurity. Now you don’t need to build your application to test it.
const isDev = require("electron-is-dev");
mainWindow = new BrowserWindow({
width: 1100,
height: 730,
'minWidth': 500,
'minHeight': 500,
webPreferences: {
nodeIntegration: true,
webSecurity: !isDev,
preload: __dirname + '/preload.js'
},
frame: isDev
});