• Stars
    star
    122
  • Rank 292,031 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 2 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐ŸŒŽโ€A react-router-dom adapter for Electron apps

Electron Router DOM

๐ŸŒŽโ€A react-router-dom adapter for Electron apps

patreon url releases url license url

preview

If you've already tried using react-router-dom with Electron, had difficulties getting it to work both in development and in production and in different windows, this library is for you!

Features

  • ๐Ÿš€ Ready for Development and Production environments
  • ๐Ÿ”ฅ Works on Multiple windows
  • ๐Ÿ“ฆ Isolated routes by window id

Installation

In your terminal, run:

yarn add electron-router-dom

# OR

npm i electron-router-dom

Router DOM is a peer dependency, if you haven't installed it yet or your package manager won't handle it automatically for you, so run:

yarn add react-router-dom

# OR

npm i react-router-dom

Usage

The main thing to keep in mind is: you must use the same window id in the Electron Main Process used in createFileRoute and createURLRoute functions and in the Electron Renderer Process in the <Router> component prop names.

Electron Main Process

import {
  app,
  BrowserWindow,
  BrowserWindowConstructorOptions as WindowOptions,
} from 'electron'

import { createFileRoute, createURLRoute } from 'electron-router-dom'
import { join } from 'path'

function createWindow(id: string, options: WindowOptions = {}) {
  const window = new BrowserWindow({
    width: 700,
    height: 473,
    ...options,
  })

  // Don't forget to check if the port is the same as your dev server
  const devServerURL = createURLRoute('http://localhost:3000', id)

  const fileRoute = createFileRoute(
    join(__dirname, '../renderer/index.html'),
    id
  )

  process.env.NODE_ENV === 'development'
    ? window.loadURL(devServerURL)
    : window.loadFile(...fileRoute)

  return window
}

app.whenReady().then(() => {
  createWindow('main', {
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
    },
  })

  createWindow('about', {
    width: 450,
    height: 350,
    show: false,
  })
})

Electron Renderer Process

Create a routes.tsx file:

import { Router, Route } from 'electron-router-dom'

import { MainScreen, AboutScreen, SearchScreen } from './screens'

export function AppRoutes() {
  return (
    <Router
      main={
        <>
          <Route path="/" element={<MainScreen />} />
          <Route path="/search" element={<SearchScreen />} />
        </>
      }
      about={<Route path="/" element={<AboutScreen />} />}
    />
  )
}

Then, import the AppRoutes in your index.tsx:

import ReactDom from 'react-dom/client'
import React from 'react'

import { AppRoutes } from './routes'

ReactDom
  .createRoot(document.querySelector('app') as HTMLElement)
  .render(
    <React.StrictMode>
      <AppRoutes />
    </React.StrictMode>
  )

A simple example of a MainScreen component:

import { useNavigate } from 'react-router-dom'

// The "App" comes from the context bridge in preload/index.ts
const { App } = window

export function MainScreen() {
  const navigate = useNavigate()

  return (
    <main>
      <button onClick={() => navigate('/search')}>Go to Search screen</button>

      <button onClick={App.OpenAboutWindow}>Open About window</button>
    </main>
  )
}

API

Electron Main Process

createFileRoute

Creates the route for Electron Window loadFile method for production mode with the given window ID.

Params:

  • path: string
  • id: string
  • options?: Electron.LoadFileOptions

Return:

  • Array: [string, Electron.LoadFileOptions]

Example:

mainWindow.loadFile(
  ...createFileRoute(
    join(__dirname, '../renderer/index.html'),
    'main'
  )
)

createURLRoute

Creates the URL route for Electron Window loadURL method for development mode for the given window ID.

Params:

  • route: string
  • id: string

Return: String

Example:

// Don't forget to check if the port is the same as your dev server
mainWindow.loadURL(
  createURLRoute(
    'http://localhost:3000',
    'main'
  )
)

Electron Renderer Process

Router

The prop names should be the window ids used in main process passsing a Route component to be rendered when route/window matches

Props: [windowID: string]: JSX.Element

Example:

<Router
  main={<Route path="/" element={<MainScreen />} />}
  about={<Route path="/" element={<AboutScreen />} />}
  settings={<Route path="/" element={<SettingsScreen />} />}
/>

Multiple Routes in the same window

<Router
  main={
    <>
      <Route path="/" element={<MainScreen />} />
      <Route path="/search" element={<SearchScreen />} />
    </>
  }
/>

Route

It's the react-router-dom <Route /> component, same props, same usage. ๐Ÿ˜„

In-depth example

The recommended way to go to handle window states between main and renderer process (like creating or closing a new window) is using IPC. You can check the electron-app boilerplate to see how it was achieved, like:

Contributing

Note: contributions are always welcome, but always ask first, โ€” please โ€” before work on a PR.

That said, there's a bunch of ways you can contribute to this project, like by:

  • ๐Ÿชฒโ€Reporting a bug
  • ๐Ÿ“„โ€Improving this documentation
  • ๐Ÿšจโ€Sharing this project and recommending it to your friends
  • ๐Ÿ’ตโ€Supporting this project on GitHub Sponsors or Patreon
  • ๐ŸŒŸโ€Giving a star on this repository

License

MIT ยฉ Dalton Menezes

More Repositories

1

aura-theme

โœจโ€A beautiful dark theme for your favorite apps.
TypeScript
3,190
star
2

electron-screen-recorder

๐Ÿ“ผโ€A Desktop screen recorder app built using web technologies for Mac, Linux and Windows.
JavaScript
291
star
3

electron-app

๐Ÿ’…โ€A fast and ready-to-go with a well-thought-out structure Electron app boilerplate with ReactJS, TypeScript, CSS / SASS modules, Electron Vite, Eslint, Prettier, GitHub Action releases and more.
TypeScript
271
star
4

interprocess

๐Ÿ’ฌโ€A scalable and type-safe Electron IPC management tool with enhanced DX
TypeScript
95
star
5

use-exit-intent

๐Ÿ โ€A React Hook to handle exit intent strategies
TypeScript
81
star
6

hyper-init

โšกโ€The ultimate and most complete extension to initialize commands before and after Hyper terminal starts.
JavaScript
75
star
7

netflix-list-exporter

๐Ÿ’ซโ€Žโ€Žโ€Žโ€โ€โ€Žโ€An Extension to export your lists from Netflix to Clipboard area and share it with your friends.
JavaScript
74
star
8

aircnc

โ˜• Airbnb like (Air Coffee & Code) to booking spots for developers using ReactJS, React Native, Node.js and more.
JavaScript
53
star
9

opendocs

๐ŸŽ‰โ€Next.js beautifully designed template that you can use for your projects for free with site, blog and docs support. Accessible. Customizable. Open Source with i18n support.
TypeScript
47
star
10

cra-template-good-start

๐Ÿ’…โ€A Create React App good starting point template to init a configured app with typescript, sass, eslint, prettier and more
TypeScript
35
star
11

stylish-hub

๐Ÿน A browser extension that brings new GitHub features and experience.
JavaScript
18
star
12

discord-malicious-domains

๐Ÿค–โ€A list of malicious domains on Discord using the Discord Guardian Action.
15
star
13

daltonmenezes.github.io

๐Ÿš€โ€My personal website.
TypeScript
13
star
14

orb

๐ŸŒ Your friendly JavaScript languages handler. ORB turns fastly and easily your website/project to multilingual.
JavaScript
13
star
15

pepper-the-chicken

A free and open source simple game that looks like Flappy Bird written in HTML5 and JavaScript.
JavaScript
11
star
16

be-the-hero

๐ŸŒŸ App to help NGOs built with ReactJS, React Native, Node.js and more.
JavaScript
10
star
17

what-type-is

โ” A simple type checking library for Node.js
JavaScript
7
star
18

discord-guardian-action

๐Ÿค–โ€An action that fetches the list of malicious domains on Discord in different providers and creates/updates a JSON file with them from time to time.
TypeScript
7
star
19

slimp

A dead simple way to build elegant websites
4
star
20

assets

Repo to store some of my public project assets
4
star
21

omelete-tabs

๐Ÿณ Extensรฃo que traz as รบltimas notรญcias do omelete.com.br nas abas do navegador.
JavaScript
2
star
22

minimal-husky-commitlint

โšกโ€A minimal template project to get started with husky and commitlint
Shell
2
star
23

eventScheduler

A simple event scheduler application for PHP projects.
PHP
2
star
24

ubuntu-wallpaper-fix

๐Ÿšโ€A shell script trick for wallpaper bug when Ubuntu is started with two (or more) connected monitors with different display interfaces.
Shell
2
star
25

linketheme

๐ŸŽจ An eye-catching cleaner theme extension for LinkedIn
CSS
2
star
26

daltonmenezes

1
star
27

code-replicator

๐Ÿฐ A piece of cake way to backup or restore settings, snippets and extensions from Visual Studio Code
1
star
28

awesome-html5-game-dev

An awesome list about game development using HTML5 technologies.
1
star
29

colors-convert-issue-examples

https://github.com/ilariaventurini/colors-convert/issues/15
TypeScript
1
star
30

researches

๐Ÿ”ฌ Stuff about my researches in software development
C
1
star