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: res.data.data });}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

Comments

Mohamed Atef Date : 2021-11-22

Best answers

51

Best answers

51

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 web-brackets.com

 

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

React Redux : Connect is not called
Publish date: 2022-03-02 | Comments: 1

Tag: React js

React.Fragment. React.Fragment can only have key props and children
Publish date: 2022-08-06 | Comments: 2

Tag: React js

npm install @mui/material returns error
Publish date: 2022-04-02 | Comments: 1

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

React Component setState doesn't update my property
Publish date: 2022-03-29 | Comments: 2

Tag: React js

How to use Datepick of Mui with Formik
Publish date: 2022-02-14 | Comments: 7

Tag: React js