Home > Mobile >  React router changes url but not loading view
React router changes url but not loading view

Time:05-31

React router changes the url but not refreshing the page. Also if I manually type url and hit ENTER then the routes works properly but on clicking the navlink it won't work.

App.js

import './App.css';
import NavLinks from './compnents/Navbar/NavLinks'
import Home from './compnents/Home/Home';
import About from './compnents/About/About';
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";


function App() {
  return (
    <>
      <Router>
        <Switch>
          <Route exact path="/" render={() => {
            return (
              <>
                <NavLinks />
                <Home />
              </>
            )
          }}>
          </Route>
          <Route exact path="/about" render={() => {
            return (
              <>
              <h1>Hello from</h1>
                <NavLinks />
                <About />
              </>
            )
          }}>
          </Route>
        </Switch>
      </Router>
    </>
  );
}

export default App;

File for navlink in which Link is added on which it sets the url NavLinks.js

import { useState } from "react";
import { Link } from 'react-router-dom';
import Logo from "./Logo";
import Container from "../GlobalComponents/Container";


const NavLinks = (props) => {
  const [hidden, setHidden] = useState(true);

  return (
    <nav>
      <Container>
        <Logo />
        <i
          onClick={() => setHidden(!hidden)}
          className={hidden ? "fas fa-bars fa-lg" : "fas fa-times fa-lg"}
          id="burgerMenu"
        ></i>
        <Link to='/'>Home</Link>
        <Link to='/about'>About</Link>
      </Container>
    </nav>
  );
};


export default NavLinks;

On click in NavLink it changes url but not loading the view. Kindly help me. I've also tried with other answers but nothing works.

CodePudding user response:

You can use the render prop in <Route> but if you're using the latest version then it is no more supported.

Instead of that, you've two methods

  1. Replace render with component prop.

  2. <Route path="/">
      {Your component}
    </Route>
    

CodePudding user response:

<Link to={} /> only seems works when accessed within the router, if outside of router you would be better off just using <a href={} />.

I have been struggling with the same thing myself before.

When is say within the router I mean something like this:

<Router>
  <head>
    <Link to={"/contactUs"}>Contact us</Link>
  </head>
  <Routes>
    <Route path={"/contactUs"} element={<ContactUs/>} />
  </Routes>
</Router>
  • Related