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>
);}
}
Use the window. location. replace() method to redirect to an external url in React, e.g. window.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With