In the context of a react project, I want to generate radio buttons for each element in an array.
Here the tags I need to render dynamically each time:
<input type="radio" name="debt-amount" id="3" value="3" required />
<label for="3"></label>
1/ Inside my form tag, I first mapped through my array like this :
data.slides.map( (item, Idx) =>
<input className={item.introline} key={Idx} type="radio" name="debt-amount" id={Idx} value={Idx} required />
<label for={Idx}><label />
)
It would log me errors in the console as I need to wrap all tags inside a parent tag.
2/ So I then tried wrapping input inside label :
data.slides.map( (item, Idx) =>
<label for={Idx}>
<input className={item.introline} key={Idx} type="radio" name="debt-amount" id={Idx} value={Idx} required />
<label />
)
This time it generated my radio buttons, but I wasn’t able to get them checked. Indeed, I added some styles in my css, and a small black dot (".") was supposed to appear inside a checked. But it didn’t for some reason…
3/ When I manually render input+label, it does work, but I would have to add these each time an element is added to the array. That is not what I want.
_
Is there a way to dynamically render label+input for Each element inside my array (in a way that it just work) ?
2
Answers
Your approach was close.
Yes you can use map function to dynamically render label input for each elements inside your array.
I think so this will helps for you as well.