Created
April 28, 2017 18:08
-
-
Save chrisguitarguy/d6086eb6d16d38e78b88c69b447fd5b3 to your computer and use it in GitHub Desktop.
Some wonky stuff can happen when you try to nest things inside `Router` components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { BrowserRouter, Route, Switch } from 'react-router-dom'; | |
function App({ children }) { | |
return <div>{children}</div>; | |
} | |
function Home() { | |
return <p>Hello, World</p>; | |
} | |
function NotFound() { | |
return <p>Not Found</p>; | |
} | |
// does not work because the children of `<App>` never actually change! | |
// the route components are declared all in advance, and are always there | |
// despite the fact that they render diferently depending on the URL | |
function Root() { | |
return ( | |
<BrowserRouter> | |
<App> | |
<Switch> | |
<Route exact path="/" component={Home} /> | |
<Route component={NotFound} /> | |
</Switch> | |
</App> | |
</BrowserRouter> | |
); | |
} | |
ReactDOM.render(<Root />, document.getElementById('app')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Children } from 'react'; | |
import ReactDOM from 'react-dom'; | |
import { BrowserRouter, Route, Switch } from 'react-router-dom'; | |
function App({ children }) { | |
return <div>{children}</div>; | |
} | |
function Home() { | |
return <p>Hello, World</p>; | |
} | |
function NotFound() { | |
return <p>Not Found</p>; | |
} | |
// this works fine, however because the Router component has moved inside the | |
// <App> Even though the children to `App` won't change, the browser router's | |
// state can and it can re-render as it sees fit | |
function Root() { | |
return ( | |
<App> | |
<BrowserRouter> | |
<Switch> | |
<Route exact path="/" component={Home} /> | |
<Route component={NotFound} /> | |
</Switch> | |
</BrowserRouter> | |
</App> | |
); | |
} | |
ReactDOM.render(<Root />, document.getElementById('app')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment