Reputation: 4641
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
Upvotes: 3
Views: 1038
Reputation: 41
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>
);
}
}
Upvotes: 1
Reputation: 1520
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.
Upvotes: 3
Reputation: 1894
BrowserRouter
<Switch>
arround <BrowserRouter>
tag<Switch>
elementYou 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
Upvotes: 2