🌎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

tiny, flexible, HOC for rendering route breadcrumbs with react-router v4 & 5

React Router Breadcrumbs HOC A small (~1.3kb compressed & gzipped), flexible, higher order component for rendering breadcrumbs with react-router 5 exa

Releases(v1.0.0)
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 1 Dec 12, 2021
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 11 Sep 21, 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à 350 Sep 22, 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 Aug 4, 2022
Render isomorphic React + React Router apps and components in Node

Render isomorphic React + React Router apps and components in Node

Sequence Media 2 Sep 15, 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 Sep 13, 2022
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 411 Aug 27, 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 870 Aug 26, 2022