How to use React on Electron app
If you’ve spun up a fresh Electron app with Electron Forge + Vite and want React, here’s the quickest way I’d do it (plus a couple gotchas I ran into).
TL;DR
- Install React and the Vite React plugin.
- Put the React plugin in the renderer Vite config (not the main process).
- Use a
.tsxentry for the renderer. - Point Forge to your renderer Vite config.
1. Install React
|
|
2. Set up the renderer Vite config
Create a renderer config dedicated to the UI and enable the React plugin.
vite.renderer.config.mts
|
|
Make sure your Forge plugin points at this file:
forge.config.ts (renderer section)
|
|
Tip: Keep React plugin out of the main process config. It’s only for the renderer.
3. Fix ESM/require config issues (if any)
If you previously had @vitejs/plugin-react inside vite.main.config.ts, you’ll likely see an “ESM file cannot be loaded by require” error. Move that plugin to the renderer config and keep your main config minimal (or rename it to .mts if you really need ESM).
Example minimal main config:
vite.main.config.mts
|
|
4. Use a TSX renderer entry
Create a React entry point and render your app.
src/renderer/index.tsx
|
|
src/App.tsx
|
|
5. Hook the HTML to the renderer entry
Your Vite dev HTML should point to the renderer entry.
index.html (project root)
|
|
6. TypeScript JSX setting
Make sure your tsconfig supports JSX:
tsconfig.json
|
|
7. Start it up
That’s it! Now let’s run the app:
|
|
Troubleshooting
If the window opens but React isn’t rendering, open DevTools and make sure:
- The HTML has a div#root.
- The script tag points to
/src/renderer/index.tsx. - No JSX is inside
.tsfiles (use.tsx).