69

Using this boilerplate as reference I created an Electron app. It uses webpack to bundle the scripts and express server to host it.

Webpack config is practically same as this and server this.

Electron's script loads:

mainWindow.loadURL('file://' + __dirname + '/app/index.html');

And index.html loads the script hosted by the server:

<script src="http://localhost:3000/dist/bundle.js"></script>

I run electron index.js to build the app and node server to start server which using webpack bundles the scripts.

It works fine, my React component App is mounted. But how I integrate react-router into this?

I implemented it the same way I would in a browser app. I get this error:

[react-router] Location "/Users/arjun/Documents/Github/electron-app/app/index.html" did not match any routes

It is taking file path as the route. Going through the boiler plate code did not help. What am I missing?

Frozen Crayon
  • 5,172
  • 8
  • 36
  • 71

9 Answers9

151

Had to Replace BrowserRouter with HashRouter.

import {
  HashRouter,
  Route
} from "react-router-dom";

And then in my index.js or the entry file of the Electron app I had something like this:

<HashRouter>
  <div>
    <Route path="/" exact     component={ Home } />
    <Route path="/firstPage"  component={ FirstPage } />
    <Route path="/secondPage" component={ SecondPage } />
  </div>
</HashRouter>

And then everything just worked.

The reasoning: BrowserRouter is meant for request-based environments whereas HashRouter is meant for file-based environments.

Read more here:

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
  • 12
    Man! you saved my entire week! I tried trillions of combinations and googled it like for ever.. Now, it works like charm! thank you – IWIH Sep 14 '18 at 14:52
  • 1
    @IWIH I had the exact same week so when I found out how to do it I thought I better share it save some other poor soul. Glad it saved you some time and sanity! =-) – Joshua Pinter Sep 14 '18 at 18:24
  • literally* (facepalm) – scarably Jun 25 '19 at 21:51
  • In my case this solution didn't helped. I'm still getting a blank page :( – Kingalione Jan 20 '20 at 15:20
  • 1
    Thank you so much it's working like a charm❤️ you saved my entire project. – Mohamed Jakkariya May 20 '21 at 10:20
  • @JoshuaPinter i created a menu item. now i wanted to navigate to another page of my application. i am using react Hash Router. Not sure where do start – Aman Deep Oct 04 '21 at 08:35
  • I tried this answer, but still, get a blank page – Darryl RN Feb 22 '22 at 06:13
  • @Kingalione Wasn't working for me either until I explicitly set in my webpack config the `devServer.historyApiFallback` property in to `true`. https://webpack.js.org/configuration/dev-server/#devserverhistoryapifallback – Antoine Dahan May 05 '22 at 19:53
  • For anyone still getting a blank page, you're likely not including a `#` in `mainWindow.loadURL('file://index.html#/home')`. Check out [my answer](https://stackoverflow.com/a/72563347/15959847) for details. – McKinley Jun 09 '22 at 16:03
  • seems promising but reactrouter.com/en/6.14.2/router-components/hash-router says "We strongly recommend you do not use HashRouter unless you absolutely have to." which makes me bit uneasy – ozgeneral Jul 21 '23 at 17:37
  • @ozgeneral This answer was from 5 years ago. What are they saying to use as an alternative now? – Joshua Pinter Jul 21 '23 at 19:05
  • I asked them here: https://github.com/remix-run/react-router/discussions/10724 it seems like people still use HashRouter although it is deprecated now – ozgeneral Jul 23 '23 at 11:31
32

Another option would be to use hashHistory instead. Actually, in your referenced repo you can see that they're using hashHistory, how about trying that and posting back?

Scott Coates
  • 2,462
  • 5
  • 31
  • 40
aestrro
  • 963
  • 10
  • 10
  • HashRouter is deprecated, so I went with Niekert's answer. https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md – user1132959 Sep 01 '17 at 20:15
  • 4
    `HashRouter` is not deprecated in 2019. – Slbox Oct 08 '19 at 20:29
27

I'm using React Router v4 and didn't want to fallback to the HashRouter, so I solved it with something amongst the likes of:

import { Redirect, BrowserRouter } from 'react-router-dom';

const App = () => (
  <BrowserRouter>
    <div>
      {window.location.pathname.includes('index.html') && <Redirect to="/" />}
    </div>
  </BrowserRouter>
);
Niekert
  • 917
  • 1
  • 8
  • 20
  • 4
    Your solution works except reloading electron will lead to a blank page. It's not a problem in "production" but in development I often need to reload. Does it happen to you? – Kev Jan 27 '18 at 18:32
  • Worked in terms of loading the app but all imported assets (images/vids) are not loaded! – Osama_Almaani Oct 02 '21 at 22:15
21

Best option at the time of this answer is to use the MemoryRouter, worked for me :)

Gabriel Matusevich
  • 3,835
  • 10
  • 39
  • 58
8

The (current) react-router docs say:

Generally speaking, you should use a <BrowserRouter> if you have a server that responds to requests and a <HashRouter> if you are using a static file server.

An Electron app is basically a static file server.

MemoryRouter can also work, so long as all routing originates from within the React part of the app. It only falls down when you want to navigate to a specific page from the Browser process, e.g. you want to pop up a new window and navigate directly to a "General Preferences" page. In that case, you can do this with HashRouter:

prefsWindow.loadURL(`file://${__dirname}/app/index.html#/general-prefs`);

I don't think there is a way to do that with MemoryRouter (from the Browser process).

J. Perkins
  • 4,156
  • 2
  • 34
  • 48
8

What about simply using Switch to default to "/" as follows:

<Switch>
  <Route path="/" exact component={Home}/>
  <Route path="/foo" component={Foo}/>
  <Route path="/bar" component={Bar}/>
  <Route render={() => <Redirect to="/"/>}/>
</Switch>

This way, "/index.html" will redirect to "/"

ChisholmKyle
  • 449
  • 3
  • 10
3

Agree with Niekert. But I believe it is better to handle like this before any route management.

if ( window.location.pathname.includes('index.html') ) {
    location.pathname = ROUTES.ROOT;
}
Arseniy-II
  • 8,323
  • 5
  • 24
  • 49
3

It all depends on what kind of URL you pass to mainWindow.loadURL.

file://...

If you load index.html directly through the file:// protocol, such as

mainWindow.loadURL('file://' + path.join(__dirname, '../index.html#/home'))

then you need to use HashRouter:

<HashRouter>
  <Routes>
    <Route path='/home' element={<MyHomeScreen/>}>
  </Routes>
</HashRouter>

Note that the # in index.html#/home is very important!

Why?

Think about what would happen if you wrote index.html/home. Your computer would try to retrieve a home file inside an index.html directory. The # prevents this, and thus we need to use HashRouter.

http://localhost:3000

If you load index.html from a server such as localhost:3000, then you have two options:

  • include the #, as in
    mainWindow.loadURL('http://localhost:3000#/home')
    
    and use HashRouter exactly as above,

OR

  • don't include the #, as in
    mainWindow.loadURL('http://localhost:3000/home')
    
    and use BrowserRouter like this:
    <BrowserRouter>
      <Routes>
        <Route path='/home' element={<MyHomeScreen/>}>
      </Routes>
    </BrowserRouter>
    

Many people prefer to use BrowserRouter in this case because it avoids complicating the URL with a #.

McKinley
  • 1,123
  • 1
  • 8
  • 18
0

In your main process:

mainWindow.loadURL(resolveHtmlPath('index.html'));

In your renderer process:

import { HashRouter as Router, Routes, Route } from 'react-router-dom';

//...

<Router>
  <Routes>
    <Route path="/" element={<Home />} />
    <Route path="/search" element={<Search />} />
    <Route
      path="/library"
      element={<Library />}
      />
  </Routes>
</Router>

The call to resolveHtmlPath removed the need for using hashtags for me. Using a BrowserRouter out of the box gave me the warning message in dev tools.

This function is in the Electron React Boilerplate project that you referenced:

import { URL } from 'url';
import path from 'path';

export function resolveHtmlPath(htmlFileName: string) {
  if (process.env.NODE_ENV === 'development') {
    const port = process.env.PORT || 1212;
    const url = new URL(`http://localhost:${port}`);
    url.pathname = htmlFileName;
    return url.href;
  }
  return `file://${path.resolve(__dirname, '../renderer/', htmlFileName)}`;
}
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80