Agenda:

This article explains usage of electron & react together to build an desktop application. As a prerequisites, you should have basic knowledge of Electron JS and React JS. Let us get started.

Get started:

Setting environment:

  • Install React and Creating an React app with following command. npx create-react-app react-electron.
    **npx installs react and its dependencies also creates named app.
  • Install Electron JS by executing npm i electron --save-dev.
    **it installs electron as dev dependency.

Add main.js at root of your project and code snippet below:

  1. const { app, BrowserWindow } = require("electron");
  2. const path = require("path");
  3. const url = require("url");
  4.  
  5. let win;
  6.  
  7. function createWindow() {
  8. win = new BrowserWindow({ width: 800, height: 600 });
  9.  
  10. // load the build folder from React
  11. win.loadURL(
  12. url.format({
  13. pathname: path.join(__dirname, `/build/index.html`),
  14. protocol: "file:",
  15. slashes: true
  16. })
  17. );
  18.  
  19. win.on("closed", () => {
  20. win = null;
  21. });
  22. }
  23.  
  24. app.on("ready", createWindow);
  25.  
  26. // on macOS, closing the window doesn't quit the app
  27. app.on("window-all-closed", () => {
  28. if (process.platform !== "darwin") {
  29. app.quit();
  30. }
  31. });
  32.  
  33. // initialize the app's main window
  34. app.on("activate", () => {
  35. if (win === null) {
  36. createWindow();
  37. }
  38. });

Key point to note here, how win.loadURL method has been configured. Well, Now it is time to update package.json as follows:

  1. {
  2. ...
  3. "main":"main.js",
  4. "homepage": "./",
  5. ....
  6. "scripts": {
  7. ...
  8. "electron": "react-scripts build && electron ."
  9. ...
  10. },
  11. }
  12.  

Here you go !! time to start our application. npm run electron. and We have react component loaded in an electron window.

Conclusion:

In this article we learnt using electron along with react to build a desktop application.

Good Bye 👋 !! until I write again. Code well, Cook good.