Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use React Router with Electron?

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?

like image 449
Frozen Crayon Avatar asked Apr 08 '16 17:04

Frozen Crayon


People also ask

When should I use HashRouter?

HashRouter: When we have small client side applications which doesn't need backend we can use HashRouter because when we use hashes in the URL/location bar browser doesn't make a server request. BrowserRouter: When we have big production-ready applications which serve backend, it is recommended to use <BrowserRouter> .

What is HashRouter in react JS?

A <Router> that uses the hash portion of the URL (i.e. window. location. hash ) to keep your UI in sync with the URL.


1 Answers

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:

  • https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/docs/api/HashRouter.md
like image 66
Joshua Pinter Avatar answered Sep 21 '22 00:09

Joshua Pinter