Search code examples
javascripthtmlcssreactjsradio-group

Dynamically generate radio group from json


I'm building a ballot app and I want to dynamically generate a radio group based on a list of candidates in an object. The object looks like this.

{
  "districtAttorney": [{
      "name": "Candidate1",
      "politics": "Dem-District 21",
      "img": "./Candidates/uncleruckus.jpg"
    },
    {
      "name": "Candidate2",
      "politics": "Dem-District 21",
      "img": "./Candidates/uncleruckus.jpg"
    }
  ]
}

I want to generate a radio group that looks like this

<div onChange={this.onChangeValue}>
            <input type="radio" value="Candidate1" name="gender" /> Male
            <input type="radio" value="Candidate2" name="gender" /> Female
            <input type="radio" value="Candidate3" name="gender" /> Other
</div> 

How would I go about this? Thanks in advance.


Solution

  • I would suggest something like this:

    const obj = result.obj //or whatever your object name is
    return (
    <div onChange={this.onChangeValue}>
        {obj.districtAttorney.map((cand, ind) => (
           <label>
             <input type="radio" value={cand.name} name="gender" />
             <span>{cand.name}</span>
           </lable>
        }
    </div> 
    

    Within the map function you can use all data from the json object