I have two links that fetches the sample component but when I click on any one of them it gets loaded and when I click on another one it won't re-render only url gets changed. I want to re-render the component on both link clicks. Is there any way to do that??
use location hook.
const location = useLocation();
const renderDOM = () => {
// return your DOM, e.g. <p>hello</p>
}
useEffect(() => {
// re render your component
renderDOM();
},[location]);
return (
<>
{renderDOM()}
</>
);
I was facing similar issue sometime back when I was working on a react project.
You need to use componentWillReceiveProps function in your component.
componentWillReceiveProps(nextProps){
//call your api and update state with new props
}
UPDATE
For react version 16.3+ please use componentDidUpdate
componentDidUpdate (prevProps, prevState) {
// update state
}
To make it more clear when your component loads for the first time by calling url www.example.com/content/a componentDidMount()
is run.
Now when you click another link say www.example.com/content/b same component is called but this time prop changes and you can access this new prop under componentWillReceiveProps(nextProps)
which you can use to call api and get new data.
Now you can keep a common function say initializeComponent()
and call it from componentDidMount()
and componentWillReceiveProps()
Your router would look something like this:-
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/content" component={app}>
<IndexRoute component={home}/>
<Route path="/content/:slug" component={component_name} />
</Route>
</Router>
), document.getElementById('app'));
So now when you call www.example.com/content/a, a would be taken as slug. Within that component if you call www.example.com/content/b , b would be taken as slug and would be available as nextProps parameter in componentWillReceiveProps.
Hope it helps!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With