React-router: [v4] How to use BrowserRouter with multiple DOM subtrees?

Created on 26 Sep 2016  路  7Comments  路  Source: ReactTraining/react-router

I have the issue, that I want to use the v4 BrowserRouter with multiple DOM subtrees. We are migrating a legacy app step by step and have to render the main navigation outside of the remaining React app. Till now, it worked quite well to push / pop routes to our history (from context). With v4 this seems no longer possible. Any ideas how to solve it?

Most helpful comment

@esturcke You are rendering a <BrowserRouter> that has been aliased as <Router>, not an actual <Router>. Switch to import { Router } from 'react-router-dom' and it should work. I put together a small example here https://codesandbox.io/embed/KZRW1gwWl.

All 7 comments

Do you mean something like this?

<Router>
  <Header/>
  <App/>
  <Footer/>
</Router>

In which case, the best option right now is to wrap it all in a <div>. See #3837

I have what I think to be the same question. If I attach React to multiple parts of the DOM in a legacy application:

ReactDOM.render(<Nav/>, document.getElementById("nav")
ReactDOM.render(<App/>, document.getElementById("app")

I tried to add a <BrowserRouter> to each component, but a <Link> in the <Header> only updates the URL, not routes in <App>. Is this something that is supported?

You have to create a history instance from the history library and use just <Router history={history}> in each of those renders.

I'm missing something. I have something like the following now:

import React from "react"
import ReactDOM from "react-dom"
import { BrowserRouter as Router } from "react-router-dom"
import createBrowserHistory from "history/createBrowserHistory"

const Nav = ({ history }) => <Router history={history}>...</Router>
const App = ({ history }) => <Router history={history}>...</Router>

const history = createBrowserHistory()
ReactDOM.render(<Nav history={history}/>, document.getElementById("nav")
ReactDOM.render(<App history={history}/>, document.getElementById("app")

<Link>s in <Nav> affect the history there, but not in <App>.

@esturcke You are rendering a <BrowserRouter> that has been aliased as <Router>, not an actual <Router>. Switch to import { Router } from 'react-router-dom' and it should work. I put together a small example here https://codesandbox.io/embed/KZRW1gwWl.

Bingo, thanks @pshrmn and @timdorr! This is working great now.

BTW, you'll get a warning about that soon: #5151

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sarbbottam picture sarbbottam  路  3Comments

ArthurRougier picture ArthurRougier  路  3Comments

andrewpillar picture andrewpillar  路  3Comments

stnwk picture stnwk  路  3Comments

jzimmek picture jzimmek  路  3Comments