Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect without flickering in React using React Router?

Tags:

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>
    );}
}
like image 288
OlegArsyonov Avatar asked Jun 16 '19 18:06

OlegArsyonov


People also ask

How do I redirect an external link with a react Router?

Use the window. location. replace() method to redirect to an external url in React, e.g. window.

Does react redirect refresh page?

react-router-dom allows us to navigate through different pages on our app with/without refreshing the entire component. By default, BrowserRouter in react-router-dom will not refresh the entire page.


1 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');
like image 124
Tiisetso Tjabane Avatar answered Oct 01 '22 00:10

Tiisetso Tjabane