I am fairly new to react but I have been told when making a website its good practice to have a layout component which holds the header, page content and footer however when using react router I want the header and footer to not update just the page content but if I add the links in the header outside the browserrouter tag I get a error saying they need to be inside but if i then include them inside the header updates along with the content..
In the header I have a navbar with links like this:
import React from 'react';
import { Link } from 'react-router-dom';
const Header = () => {
return(
<nav className="header-links">
<Link to="/" className="link">Home</Link>
<Link to="/about" className="link">About</Link>
<Link to="/contact" className="link">Contact Us</Link>
</nav>
);
}
export default HeaderNav;
Then in the layout file I include the header which has the links
import React from 'react'
import Header from './header/header'
import Footer from './footer/footer'
const PageLayout = ({children}) => {
return (
<div className="layout-wrapper">
<Header />
<main className="site-content">{children}</main>
<Footer />
</div>
);
}
export default PageLayout;
Then I also have a router file with my routes:
import React from 'react'
import HomePage from './pages/home'
import AboutPage from './pages/about'
import ContactPage from './pages/contact'
import {
Switch,
Route,
BrowserRouter
} from 'react-router-dom';
const Routes = () => (
<BrowserRouter>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/contact" component={ContactPage} />
</Switch>
</BrowserRouter>
);
export default Routes;
The problem that I am having is if in the layout.js I only wrap the page content in the browserrouter tag then I get a error saying my links need to be inside this BUT if I then wrap the header, page content and footer in the browserrouter then they all update when a link is clicked so I am struggling with how do I include the links in the browserrouter without the header updating?
For instance:
import React from 'react'
import Header from './header/header'
import Footer from './footer/footer'
const PageLayout = ({children}) => {
return (
<div className="layout-wrapper">
<Routes>
<Header />
<main className="site-content">{children}</main>
<Footer />
<Routes />
</div>
);
}
export default PageLayout;
I might be totally off base here, but I'm pretty sure you want something like this:
<BrowserRouter>
<Header/>
<Switch>
<Route exact path="/" component={HomePage} />
<Route exact path="/about" component={AboutPage} />
<Route exact path="/contact" component={ContactPage} />
</Switch>
<Footer />
</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.