I have a Main page that contains 4 section ** #home, #collection, #products and #contact** and I have 2 different page for /cart and /login Navbar Code is Here
`<nav>
<div className='wrap-nav'>
<NavLink href="" className='logo'>NILESTORE</NavLink>
<div className='wrap-ul'>
<ul className='nav-links' >
<li><NavLink to="#home">Home</NavLink></li>
<li><NavLink to="#collection">Collection</NavLink></li>
<li><NavLink to="#products">Products</NavLink></li>
<li><NavLink to="#contact">Contact</NavLink></li>
</ul>
<ul className='nav-items'>
<li><NavLink to="/cart" className='cart' data-item={data.cartItems.length}><BsBag /></NavLink></li>
<li><NavLink to="/login" className='login'>Login</NavLink></li>
</ul>
</div>
</div>
</nav>`
App.js code is here
import React from 'react'
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css"
import Navbar from './components/Navbar'
import Cart from './pages/Cart';
import Main from './pages/Main';
function App() {
return (
<>
<Router>
<Navbar />
<Routes>
<Route path="/" element={<Main />} />
<Route path="/cart" element={<Cart />} />
</Routes>
</Router>
</>
)
}
export default App
SO when I am in main page that works fine and I can reach that section when clicking the section like when i click on products i can reach on #products After that when I click on /cart and /login page I can reach on that page but myNavbar is same for all pages so when I click on Products, it doesn't work
I have tried all the possibilities on changing the NavLink like I have changed #products to /#products but also It doesn't work
Is there any solution for that
CodePudding user response:
I think you can do one of these two:
First You can change your navbar and when you go to a page like a login page or cart page , your navbar doesn't show the other option till the user get back to the home page.
Second is that you pass a variable when you click on those (home, collection, products, and contact). you will say okay go to the home page if I am not at the home page then you will check the state and if there was one of these variables (home, collection, products, and contact) you can navigate to them by using js.
pathname: '/somewhere',
search: '?some=search-string',
hash: '#howdy',
state: {
[userDefined]: true
}
basically, this is what you find when you use location hook.
for more information check out the website
CodePudding user response:
To navigate to a particular section of a particular page, you might want to use a HashLink in your Navbar component.
Installation:
npm i react-router-hash-link
Import it as:
import { HashLink } from 'react-router-hash-link';
And use it as:
<li><HashLink to={"/page#id"}>Contacts</HashLink></li>
You can learn more about the same here
Hope this helps!