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

46

Best answers

46

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 replaceState it'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

Warning: React.jsx: type is invalid
Publish date: 2022-05-06 | Comments: 1

Tag: React js

TypeError: Super expression must either be null or a function
Publish date: 2022-03-13 | Comments: 2

Tag: React js

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

Tag: React js

Unexpected mix of '&&' and '||' Reactjs
Publish date: 2021-10-30 | Comments: 0

Tag: React js

Could not be processed as an image because it has an invalid content type
Publish date: 2021-12-08 | Comments: 0

Tag: React js

[solved] Reactjs is not updating the props
Publish date: 2022-02-04 | Comments: 2

Tag: React js

How to get the selected object in "Autocomplete material ui"?
Publish date: 2021-12-22 | Comments: 2

Tag: React js

import link as router link from 'react-router-dom' Reactjs
Publish date: 2021-09-30 | Comments: 3

Tag: React js