Reputation: 1207
So I have that situation:
I have a MovieList
component that loop through Movie
components,
and In each Movie
Component there is Text
component that has a state to "ShowFullText" or not ( the default is not to show the full text ) and this stateful component has a button to show the full text which works just fine.
Now, let's assume you search for some other movies and then search again the Movie you expanded its text, well it's still expanded
So what I would like to know is how if the parent component (Movie
) changed, ( for example disappeared and then in the future will come back ), its sub-components state's will reset to default?
Upvotes: 0
Views: 151
Reputation: 8418
This can be done in at least two ways.
Render child components with search string passed as prop:
list.map( (movie, idx) => <Movie key={idx} searched={searched} data={movie} />)
Of course <Movie />
should react on prop change - f.e. by useEffect
(dependency - 2nd arg on [props.searched]
), shouldComponentUpdate()
(props/state saving/comparison) or getDerivedStateFromProps
.
Force recreating of all listed childs by using unique key
property, f.e. derived from search string. This can affect performance (for long lists).
list.map( (movie, idx) => <Movie key={`${idx}_${searched}`} data={movie} />)
using template literals or simple strings (first argument):
list.map( (movie, idx) => <Movie key={searched + idx} data={movie} />)
Upvotes: 1