🌎A react-router-dom adapter for Electron apps

Overview

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 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,
  })

  const devServerURL = createURLRoute(process.env['ELECTRON_RENDERER_URL']!, 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:

} /> } /> } about={} />} /> ) }">
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:

mainWindow.loadURL(
  createURLRoute(
    'http://localhost:3333',
    '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:

} />} about={} />} settings={} />} />">
<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 component, same props, same usage. 😄

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

You might also like...
React Router scroll management

react-router-scroll React Router scroll management. react-router-scroll is a React Router middleware that adds scroll management using scroll-behavior

🔼 UI-Router for React
🔼 UI-Router for React

UI-Router provides extremely flexible, state based routing to the React ecosystem.

Easy Router for Effector with React bindings

effector-easy-router A declarative router for effector and react. It is inspired by react-router-dom and effector gates. Routes are independent from e

React router that supports rendering of multiple independent (auxiliary) routes.

aux-router React router that supports rendering of multiple independent (auxiliary) routes. Install npm install --save aux-router Documentation AuxRou

A small router library for React focusing on the Developer Experience

Crossroad A routing library for React with a familiar interface. It has some differences with React Router so you write cleaner code: The links are pl

A simple and safe router for React and TypeScript.

A simple and safe router for React and TypeScript.

Code examples for our React Router 6 update video

About This Repository This repository belongs to my "React Router v6 Upgrade Guide" YouTube video. You can also learn all about React (incl. React Rou

Full page transitions with react-router.
Full page transitions with react-router.

react-tiger-transition Page transitions for react router dom. Animate your routes programmatically during navigation. Instead of defining the animatio

🗺️ Static route mapping for React Router

React Router Chart Create a single source map of truth for all routes in your react app and easily render in react-router Getting Started Install Incl

Comments
  • Handle trailing slash in `createURLRoute`

    Handle trailing slash in `createURLRoute`

    I came across this issue today where createURLRoute(import.meta.env.VITE_DEV_SERVER_URL, id) generated an invalid url because import.meta.env.VITE_DEV_SERVER_URL had a trailing /.

    The generated URL was something like http://localhost:1234//#/main.

    I was able to fix it via url.replace(/\/+$/, '') but I still think this should be handled by this package.

    opened by offirgolan 8
  • Readme is missing how to open a route in a new window

    Readme is missing how to open a route in a new window

    Currently, the readme has the following:

    // The "App" comes from the context bridge in preload/index.ts
    const { App } = window
    
    // ...
    
    <button onClick={App.OpenAboutWindow}>Open About window</button>
    

    But it's still unclear how to actually open/close the windows. Can you provide a more in-depth example or a sample application?

    opened by offirgolan 2
  • Thoughts on a `createElectronRouter` API to support v6.4 data APIs

    Thoughts on a `createElectronRouter` API to support v6.4 data APIs

    👋 Hi!

    v6.4 of react router introduced data APIs that can only be used via the createBrowserRouter, createHashRouter, and createMemoryRouter.

    Thoughts on having this library support a similar wrapper around createHashRouter?

    opened by offirgolan 7
Releases(v1.0.5)
  • v1.0.5(Nov 10, 2022)

    What's Changed

    • Update peerDependencies to support react 17 by @offirgolan in https://github.com/daltonmenezes/electron-router-dom/pull/6

    New Contributors

    • @offirgolan made their first contribution in https://github.com/daltonmenezes/electron-router-dom/pull/6

    Full Changelog: https://github.com/daltonmenezes/electron-router-dom/compare/v1.0.4...v1.0.5

    Source code(tar.gz)
    Source code(zip)
  • v1.0.4(Nov 2, 2022)

    What's Changed

    • Feat/v1.0.4 by @daltonmenezes in https://github.com/daltonmenezes/electron-router-dom/pull/5

    New Contributors

    • @daltonmenezes made their first contribution in https://github.com/daltonmenezes/electron-router-dom/pull/5

    Full Changelog: https://github.com/daltonmenezes/electron-router-dom/compare/v1.0.2...v1.0.4

    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Nov 2, 2022)

  • v1.0.0(Sep 20, 2022)

Owner
Dalton Menezes
Developer and Instructor at @Rocketseat
Dalton Menezes
React app with TypeScript - React Router Dom

React Project with - React Router Dom My name is Alex Principe. I'm a Full stack developer who shares programming code with the community. This repo c

Alex Principe 2 Sep 20, 2022
You can found the concept of react hooks, local storage, conditional rendering and react-router-dom.

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Tikaram Acharya 2 Jun 1, 2022
a more intuitive way of defining private, public and common routes for react applications using react-router-dom v6

auth-react-router is a wrapper over react-router-dom v6 that provides a simple API for configuring public, private and common routes (React suspense r

Pasecinic Nichita 12 Dec 3, 2022
:tada: Redux First History - Redux history binding support react-router - @reach/router - wouter

redux-first-history Redux First History - Make Redux 100% SINGLE-AND-ONLY source of truth! Redux history binding for react-router @reach/router wouter

Salvatore Ravidà 367 Dec 31, 2022
Redux bindings for React Router – keep your router state inside your Redux store

redux-router This project is experimental. For bindings for React Router 1.x see here In most cases, you don’t need any library to bridge Redux and Re

Andrew Clark 2.3k Dec 7, 2022
Render isomorphic React + React Router apps and components in Node

Render isomorphic React + React Router apps and components in Node

Sequence Media 3 Nov 1, 2022
A simple middleware-style router for isomorphic JavaScript web apps

Universal Router A simple middleware-style router that can be used in both client-side and server-side applications. Visit Quickstart Guide (slides) |

Kriasoft 1.6k Jan 6, 2023
named routes for react-router and your react application

react-router-namesake Example import { Switch } from "react-router"; import { BrowserRouter, Route, Link } from "react-router-dom"; import { Router as

Joe Hsu 6 Aug 12, 2021
Automatic breadcrumbs for React-Router

React Breadcrumbs React component use to generate a breadcrumb trail (compatible with React Router). Installation npm install --save react-breadcrumbs

Sven Anders Robbestad 409 Dec 9, 2022
Declarative router component for React.

React Router Component Version Compatibility >= 0.39.0 React v15,16 >= 0.32.0 React v15 >= 0.27.0 React 0.14 0.24 - 0.26.0 React 0.13 0.23 - 0.26.0 Re

Samuel Reed 871 Nov 29, 2022