1

I have been trying to figure this out for awhile but basically I have a list of tags with

tags with onClick properties that should change a state variable postsShown to true. Tricky thing is the postsShown is supposed to be an array of boolean values and uses the index to differentiate which

tag was clicked. Now the state variable does update but gets stuck and does not get detected by my conditional statement. this is my code, I have tried calling the setState function with a callback but get an error

1 Answer 1

2

Your onClick event is not changing the object just the content inside the object. Since the pointer to the object didn't change React will not re-redner your component.

change your onClick function:

onClick={()=>{
  const postsClone = [...postsShown];
  postsClone[index]= true;
  setPostsShown(postsClone);
}}

[...postsShown] will create a new reference by copying the top level of the object.

If you need to create a deep copy use

const postsClone = JSON.parse(JSON.stringify(postsShown));
Sign up to request clarification or add additional context in comments.

2 Comments

[...postsShown] will create a new reference but not a deep copy....just a deep copy of the top most level.
Thank you this worked. This has been bugging me for awhile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.