user

Joseph Morgan

22 Nov 2021

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

22 Nov 2021

githubgithubgithub

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 webbrackets.xyz

 

Replies

Joseph Morgan

22 Nov 2021

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

© 2024 Copyrights reserved for web-brackets.com