Reputation:
All I want to do is have a different Navbar for the home page and a different one for the rest of the pages. I have used things like window.location.pathname
and also withRouter
. These things only work when the page reloads. When using Link
and navigate to a new page from Home, the Navbar of the Home page remains on the other pages until I reload and vice versa.
What worked for me is using
useEffect(()=> { document.getElementById("id of home nav").style.display = "none" document.getElementById("id of regular nav").style.display = "block" },[]}
But, I have to do this on every single Component page. I wonder if there is a better way to do this. Thanks for the help.
EDIT: This is what I have tried now
"/HomeNavbar.jsx"
return (
<>
{window.location.pathname === "/" ? (
"Home Navbar Code Here"
) : null}
</>
);
};
So when I traverse from other pages to the home page this works perfectly. I wrote a similar code in my regular Navbar but am having the same issues again. The navbar only loads once I reload my page.
"/RegularNavbar.jsx"
return (
<>
{window.location.pathname === "/" ? null : (
"Regular Navbar code Here"
)}
</>
);
};
Upvotes: 1
Views: 4334
Reputation: 801
You can create two different layouts (higher order components) with different navbars and wrap the home page with layout1 and other components with layout 2
import React from 'react';
import { Link } from 'react-router-dom';
const Layout1 = (props) => (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>
<div>{props.children}</div>
</div>
);
export default Layout1;
layout 2:
import React from 'react';
import { Link } from 'react-router-dom';
const Layout2 = (props) => (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topicgdfgdgs</Link></li>
</ul>
<p>this is a different nav bar, different from the home page</p>
<div>{props.children}</div>
<hr/>
</div>
);
export default Layout2;
home component:
import React from 'react';
import Layout1 from '../Layouts/Layout1';
const Home = () => (
<Layout1>
<div>
<h2>Home</h2>
</div>
</Layout1>
);
export default Home;
any other components:
import React from 'react';
import { Link, Route } from 'react-router-dom';
import Layout2 from '../Layouts/Layout2';
const Topics = ({ match }) => (
<Layout2>
<div>
<h3>topics</h3>
</div>
</Layout2>
);
export default Topics;
Upvotes: 2