7

I'm building a SPA with React utilizing React Router and encountered this conceptual issue.

So, this is my App component, which has a React Router.

class App extends Component {
  render(){
    return(
      <div className="appwrap">
        <Jumbotron></Jumbotron>
        <Navbar></Navbar>
        <Router>
          <Route exact path="/" component={Display}></Route>
          <Route exact path="/saved" component={Saved}></Route>
        </Router>
        <Footer></Footer>
      </div>
    )
  }
}

In my Navbar component there are a couple of simple functions redirecting to href, which obviously are causing the page to 'flicker' and refresh. This is what I'm trying to get rid of (the flickering). My Navbar component is right here.

class Navbar extends Component {
  redirectToSearch = () => {
    window.location.href = '/'; 
  }
  redirectToSaved = () => {
    window.location.href = '/saved'; 
  }
  render(){
    return (
      <div className="navbar">
          <div className="navbaropt" onClick={this.redirectToSearch.bind(this)}>search</div>
          <div className="navbaropt" onClick={this.redirectToSaved.bind(this)}>saved</div>
      </div>
    );}
}
OlegArsyonov
  • 1,251
  • 1
  • 14
  • 18

2 Answers2

4

For in-page navigation with React Router you have to use the Link element.

  <div className="navbar">
      <Link to="/">search</Link>
      <Link to="/saved">saved</Link>
  </div>

Read all about it here

Avin Kavish
  • 8,317
  • 1
  • 21
  • 36
  • Why would you want to avoid the Link tag? – Avin Kavish Jun 16 '19 at 19:30
  • 2
    I can't even begin to understand what's going on here. There's nothing in your original question that remotely indicates that you do not want to use a Link tag. – Avin Kavish Jun 16 '19 at 19:31
  • 2
    Also, you can save some cycles by binding only once in the constructor as opposed to every render. But you don't even need to bind since you are using arrow functions – Avin Kavish Jun 16 '19 at 19:43
  • Agree. OP and anyone should just use `Link` instead for best practice. – Potion Sep 29 '22 at 12:28
4

I had the same problem and found the solution on the following post: Programmatically navigate using react router.

Replace window.location.href with this.props.navigation.push

update your functions to below

redirectToSearch = () => this.props.navigation.push('/');

redirectToSaved = () => this.props.navigation.push('/saved');
Tiisetso Tjabane
  • 2,088
  • 2
  • 19
  • 24