Reputation: 892
I'm trying to render a list of components using map function in render. When I change state, render function is called as expected but my component is not updated. I've made a sample codesandbox here
https://codesandbox.io/s/nk24mr55om
What am I doing wrong? I've added some console logs and it look like secret content should be displayed but it is not
Upvotes: 1
Views: 2155
Reputation: 7492
Once your item is pushed into the items
array, it will not be updated, ever. A solution to this would be to convert the items you push into arrow functions that will get a show
parameter :
items.push(show =>
<div>
{show && <div>I'm secret</div>}
My content
<br />
<input
type="button"
onClick={showSecret}
value="Show secret content"
/>
</div>
);
And then call it in the mapping of your render :
return <div key={index}>{item(show)}</div>;
However, with this solution, clicking on one button will cause every item to show their secret element, if this isn't the behavior you expect and want every item to act on its own, I suggest creating a hook for each item. And ahev them store their own show
variable in their state.
Upvotes: 1
Reputation: 1366
I have no experience yet with react hooks, but i tried to understand whats going on. The variable items you refer to is neither a prop nor in the state of your component, i would make the component stateful and initialize items in the state.
Maybe there is a better way with react hooks that someone else can give
Upvotes: 0