Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Created April 28, 2017 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisguitarguy/d6086eb6d16d38e78b88c69b447fd5b3 to your computer and use it in GitHub Desktop.
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
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'));
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