I installed react-router-dom and use this code for routing, But i have error :
import React from 'react'; import ReactDOM from 'react-dom'; import { Route, Switch } from 'react-router-dom'; class Home extends React.Component{ render(){ return( <h1>Home</h1> ); } } class About extends React.Component{ render(){ return( <h1>About</h1> ); } } ReactDOM.render( <Switch> <Route exact path='/' component={Home}/> <Route path='/about' component={About}/> </Switch>, document.getElementById('main') );
What's the right way for routing in reactjs ?
tnx
Wrap BrowserRouter
around your Switch
like below,
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route path='/about' component={About} />
</Switch>
</BrowserRouter>
Here is the working code demo in codesandbox .
BrowserRouter
<Switch>
arround <BrowserRouter>
tag <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
Kay Concepts
<BrowserRouter>
is needed because
<Route>
<Path>
<Switch>
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';
const MainContent = () => (
<main>
<Switch>
<Route exact path='/' component={Home}/>
<Route path='/about' component={About}/>
</Switch>
</main>
)
export default MainContent;
Layout.js
class Layout extends Component {
render() {
return (
<div className={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";
class App extends Component {
render() {
return(
<BrowserRoter>
<Layout />
</BrowserRouter>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.