Routing in Chrome Extension written in React

While you wouldn't want to use the browser (or hash) history for your extension, you could use a memory history. A memory history replicates the browser history, but maintains its own history stack.

import { createMemoryHistory } from 'history'
const history = createMemoryHistory()

For an extension with only two pages, using React Router is overkill. It would be simpler to maintain a value in state describing which "page" to render and use a switch or if/else statements to only render the correct page component.

render() {
  let page = null
  switch (this.state.page) {
  case 'home':
    page = <Home />
    break
  case 'user':
    page = <User />
    break
  }
  return page
}

I just had to use createMemoryHistory instead of createBrowserHistory:

import React from "react";
import ReactDOM from "react-dom";
import { Router, Switch, Route, Link } from "react-router-dom";
import { createMemoryHistory } from "history";

import Page1 from "./Page1";
import Page2 from "./Page2";

const history = createMemoryHistory();

const App: React.FC<{}> = () => {
  return (
    <Router history={history}>
      <Switch>
        <Route exact path="/">
          <Page1 />
        </Route>
        <Route path="/page2">
          <Page2 />
        </Route>
      </Switch>
    </Router>
  );
};

const root = document.createElement("div");
document.body.appendChild(root);
ReactDOM.render(<App />, root);
import React from "react";
import { useHistory } from "react-router-dom";

const Page1 = () => {
  const history = useHistory();

  return (
    <button onClick={() => history.push("/page2")}>Navigate to Page 2</button>
  );
};

export default Page1;


I solved this problem by using single routes instead of nested. The problem was in another place...

Also, I created an issue: https://github.com/ReactTraining/react-router/issues/4309


I know this post is old. Nevertheless, I'll leave my answer here just in case somebody still looking for it and want a quick answer to fix their existing router.

In my case, I get away with just switching from BrowserRouter to MemoryRouter. It works like charm without a need of additional memory package!

import { MemoryRouter as Router } from 'react-router-dom';

ReactDOM.render(
    <React.StrictMode>
        <Router>
            <OptionsComponent />
        </Router>
    </React.StrictMode>,
    document.querySelector('#root')
);

You can try other methods, that suits for you in the ReactRouter Documentation