How Routing With React-router-dom?
Solution 1:
Wrap BrowserRouter
around your Switch
like below,
<BrowserRouter><Switch><Routeexactpath='/'component={Home} /><Routepath='/about'component={About} /></Switch></BrowserRouter>
Here is the working code demo in codesandbox.
Solution 2:
- You didn't import
BrowserRouter
- You should wrap your
<Switch>
arround<BrowserRouter>
tag - Better use a component than trying to render a
<Switch>
element
You may find anything your looking for on this link :
https://reacttraining.com/react-router/web/guides/philosophy
Also i made a quick pen : https://codepen.io/FabienGreard/pen/KZgwKO?editors=1010
Solution 3:
Kay Concepts<BrowserRouter>
is needed because
- Each router creates a history object, which it uses to keep track of the current location and re-render the website whenever that changes
- A React Router component that does not have a router as one of its ancestors will fail to work.
- Router components only expect to receive a single child element. To work within this limitation, it is useful to create an component that renders the rest of your application.
<Route>
- The component is the main building block of React Router. Anywhere that you want to only render content based on the location’s pathname, you should use a element.
<Path>
- When the current location’s pathname is matched by the path, the route will render a React element.
<Switch>
- You can use the component to group s.
- The will iterate over its children elements (the routes) and only render the first one that matches the current pathname.
I think you should create different component for Routes.
I'll just explain general project structure here
You can create component to hold <Header>
and <MainContent>
As <Header>
will be same througout the application and it will not change if path changes. You can include routes in <MainContent>
which will be updated if path changes.
MainContent.js
import { Switch, Route } from'react-router-dom';
constMainContent = () => (
<main><Switch><Routeexactpath='/'component={Home}/><Routepath='/about'component={About}/></Switch></main>
)
exportdefaultMainContent;
Layout.js
classLayoutextendsComponent {
render() {
return (
<divclassName={classes.root}><Header /><MainContent /></div>
);
}
Now you can use <BrowserRouter>
to wrap your <Layout>
in App.js . or you can use it in <MainContent>
as well
App.js
import { BrowserRouter } from"react-router-dom";
classAppextendsComponent {
render() {
return(
<BrowserRoter>
<Layout />
</BrowserRouter>
);
}
}
Post a Comment for "How Routing With React-router-dom?"