user image

Joseph Morgan
Published in : 2021-11-22

How to update React router without Re-render?

React js

How can to update the Link in the component without reloading the component in the Reactjs ?
I am always using functional component and change the router using push function like the code below, but what should i use to replace the link in different case, here is example of how i usually use it 

import React from 'react';import { withRouter } from 'react-router-dom';import {Box} from '@material-ui/core';import axios from 'axios';import { BackendURL } from 'src/constants';class Blog extends React.Component {state = {posts: :null,};openPost(id){if(!id){return false;}this.props.history.push('/blog/'+id);}async getData(){try{let res = await axios.get(BackendURL+'/blog/posts');this.setState({ posts: });}catch(err){console.error(err);}}componentDidMount(){this.getData();}render(){if(!this.state.posts){return null;}return (<Box><Typography variant="body1" color="textPrimary">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation</Typography><Button variant="contained" color="primary" onClick={ () => { this.openPost(39); } }>View post</Button></Box>);}}export default withRouter(Blog);

Thanks in advance


Mohamed Atef Date : 2021-11-22

Best answers


Best answers


Hi Joseph, you can use replace function instead of push so the function can be like this 

openPost(id){if(!id){return false;}this.props.history.replace({ pathname: `/blog/${id}`});}

or you can check the documentation 
Thank you for using


Joseph Morgan Date : 2021-11-22

yea that's good also there is a function called replaceStateit's exists in the router class 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

[Solved] Cannot read properties of null (reading 'getBoundingClientRect')
Publish date: 2021-12-02 | Comments: 2

Tag: React js

useStyles Invalid hook call class component
Publish date: 2022-02-10 | Comments: 2

Tag: React js

How to use SetFieldValue from outside render function? Formik
Publish date: 2021-07-03 | Comments: 2

Tag: React js

React usestate array map() is not working
Publish date: 2022-04-22 | Comments: 3

Tag: React js

Best way to update the state in one class component from the redux store?
Publish date: 2022-03-30 | Comments: 3

Tag: React js