vendredi 25 août 2023

How to keep state of a checkbox?

I have a list of users in 3 different groups(Group A, Group B, and Group C) that I can search by their names. There's a checkbox next to each user. My issue is that even though I click on a checkbox (Example: checkbox next to Alex) and then I start typing Alex I notice my checkbox is no longer checked. I'm guessing it's because React re-renders the component every time I type a character. How can I persist the value of the checkbox? I'm open to using local storage , but what will be the implementation? Thanks in advance!

Here's my LIVE DEMO

<article>
      <h2>
        {post.label}{" "}
        <span onClick={() => setShowGroup(!showGroup)}>
          {showGroup ? "-" : "+"}
        </span>
      </h2>
      {showGroup && (
        <div>
          {post.fields?.map((field: any, idx: number) => {
            return (
              <div key={idx}>
                <input type="checkbox" name="" id="" />
                <span>{field?.name}</span>
                <br />
              </div>
            );
          })}
        </div>
      )}
</article>



Aucun commentaire:

Enregistrer un commentaire