How to redirect without flickering in React using React Router?

Viewed 6525

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>
    );}
}
2 Answers

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');

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

Related