BestYasuo
BestYasuo

Reputation: 55

How to make react router link do render

I am using React Router but somehow when I click on the Link tag nothing works. It does show up, for example when I click on the about tag, it logs the link of the Link tag /about but doesn't get me to the About Components. I have included the BrowserRouter tag in the index.js App.js

function App() {
 return (
   
   <>
       <Switch>
           <Route path="/" component={Home} />
           <Route exact path="/about" component={About} />
           <Route path="/product" component={Product}/>
           <Route path='/cart' component={Cart}/>
       </Switch>      
   </>
   
 );
}

NavBar.js with Link not working

const NavBar = () => {
    
    const [ulHeight, setUlHeight] = useState('0px');
    const menutoggle = () => {
        if (ulHeight === '0px') {
            setUlHeight('200px');
        }
        else { 
            setUlHeight('0px');
        }
    }
    const navBar = (
        <ul id="MenuItems" style={ {maxHeight: ulHeight }}>
            <li><Link to="/home">Home</Link></li>
            <li><Link to="/product">Products</Link></li>
            <li><Link to="/about">About</Link></li>
            <li><Link to="/">Contact</Link></li>
            <li><Link to="/">Account</Link></li>
        </ul>
    )
    return (

            <div class="container">
                <div class="navbar">
                    <div class="logo">
                        <img src={logo} width="125px" />
                    </div>
                    <nav>
                        {navBar}
                    </nav>
                    <Link to='/cart'><img src={cart} width="30px" class="cart" /></Link>
                    <img src={menuIcon} class="menu-icon" onClick={menutoggle} />
                </div>
            </div>
            
    )
}


Upvotes: 0

Views: 52

Answers (1)

Abrah_dago_313
Abrah_dago_313

Reputation: 210

You need to put it within the Router,

import {BrowserRouter as Router} from "react-router-dom";

or export you component using withRouter(), docs here

Upvotes: 1

Related Questions