Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

render react component when prop changes

how to force render our component when props changes? how to force render parent component when child component's props changes?

i searched a lot but all solutions are deprecated in new React version.

in my any pages (Route exact path="/post/:id" component={post}) for example (siteUrl/post/1) i am getting (:id) from props (this.props.match.params) and that works.

but when i am in single page component (Post) and this Route (siteUrl/post/1) when i am passing new Props to this component (:id).

props will changes but single component and parent component Will not re render...

like image 445
Kourosh Neyestani Avatar asked Oct 17 '22 06:10

Kourosh Neyestani


2 Answers

You may be using componentDidMount method.

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

but you need to use componentDidUpdate.

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

You can also use state and other React features without writing a class. read more: https://reactjs.org/docs/hooks-effect.html

like image 115
Ali Sharifineyestani Avatar answered Oct 20 '22 16:10

Ali Sharifineyestani


To make both parent and child re-render you need to path prop from parent to it's child.

   // parent using
   <Parent someProp={{someVal}} />

   // parent render:

   render() {
      const { someProp } = this.props
      <Child someProp={{someProp}} />
   }

this will surely re-render both components, unless you stated another logic in componentShouldUpdate

in your case Router looks like a parent for Parent so you should only path :id as a prop.

Make sure Router is at the top level, right under the App

like image 34
Igor Berezin Avatar answered Oct 20 '22 17:10

Igor Berezin