Reputation: 992
I have 3 components: Header.js
, Main.js
, and Footer.js
, and App.js
is like
const App = () => {
<Header/>
<Main/>
<Footer/>
}
In the Header.js
I have links like About
and Projects
. I would like to be able when I click About
in the header for example to display the page About.js
in Main.js
, and when I click Projects
to display the page Projects.js
in the Main.js
component. I tried to use Routing in the Main.js
component like
const Main = () => {
<Router>
<Switch>
<Route exact path='/' component={About.js} />
<Route exact path='/projects' component={Projects.js} />
</Switch>
</Router>
}
but it wouldn't allow me, saying that I cannot use Link
outside a router, where I use Link
in the Header.js
. How can I achieve this?
The Header.js
is the following
const Header = () => {
return (
<div>
<ul>
<li>
<Link to="/">
About
</Link>
</li>
<li>
<Link to="/projects">
Projects
</Link>
</li>
</ul>
</div>
)
}
Upvotes: 0
Views: 29
Reputation: 16576
You simply need to make sure your Router
component surrounds any components doing routing. For simplicity, here’s the router surrounding your whole app at the App level.
const App = () => {
<Router>
<Header/>
<Main/>
<Footer/>
</Router>
}
Edit: make sure you’re passing your components correctly to the Routes:
const Main = () => {
<Switch>
<Route exact path='/' component={About} />
<Route exact path='/projects' component={Projects} />
</Switch>
}
Upvotes: 1