Search code examples
reactjschecked

display checked in react


I'm trying to display add checked to input when i is equal to zero

I have a checked state which is a boolean so I should get checked= true and then checked= false

   lists.map( ( {  names = '' }, i ) => {
                            if(i === 0) {
                              setAttributes({checked : true});
                            }else{setAttributes({checked : false});}
                            return  <Fragment>
                                    <input className="noms" type="radio" id={ i } checked={checked}/>

but how could I get checked="checked" and then nothing like this

 <input type="radio" name="vehicle" value="Bike"> I have a bike<br>
 <input type="radio" name="vehicle" value="Car" checked="checked"> I have a car<br> 

Solution

  • This is what you need inside your Fragment:

    <input className="noms" type="radio" id={i} checked={checked ? checked : false}/>

    You don't really need a string value for the checked parameter. I always use a boolean, like this:

    <input className="noms" type="radio" id={i} checked={!!checked}/>

    Why !!? It will turn any truthy values to boolean true and any falsy values to boolean false.

    Also, you probably need a value prop somewhere.