Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React TS loop through object and get checked value

How do I get a get a value from object key when looping through it.
I currently have an object like this:

    const [brandState,setBrandState] = useState({
        Brands:{
            NewBalance: false,
            Nike: false,
            Addiddas: false,
            Converse:false,
            UnderArmour:false,
        },
});

And I am looping through it rendering checkbox inputs like this:

{
  Object.keys(brandState.Brands).map((brand)=>
  <div className="">
  <label htmlFor={brand} className="mr-[10px]">{brand}: </label>
  <input type="checkbox" name={brand} className="cursor-pointer" />
  </div>
  )
  }

Everything workouts apart from getting the value (true or false)
I tried setting checked={brand} but I get an error saying that brand is a string, I also tried checked={brandState.Brands.brand} however that also gives me an error.
How can I get the value of each key to set as the checked?
Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Alternatively to Sherry Hsu’s excelent suggestion, you can loop over entries instead of keys:

  Object.entries(brandState.Brands).map([brand, checked]=>
  <div className="">
  <label htmlFor={brand} className="mr-[10px]">{brand}: </label>
  <input type="checkbox" name={brand} className="cursor-pointer" checked={checked}/>
  </div>
  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading