Joseph Morgan
Published in : 2021-11-22
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
Join our community and get the chance to solve your code issues & share your opinion with us
Sign up Now
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
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