Home > Net >  Why does this code give an "Each child in a list should have a unique 'key' prop"
Why does this code give an "Each child in a list should have a unique 'key' prop"

Time:04-23

If I replace the fragment (<> </>) with a div and give it a key I no longer get the error but that also screws up my button group. Each of these elements has a unique key and the fragment should not be a dom element so why this error? Any suggestions on a solution?

{["long", "short", "out", "none"].map(stance =>
           <>
               <input type="radio" className="btn-check" id={stance} key={stance}
               autoComplete="off" checked={options.stance === stance} disabled={options.auto}/>
               <label key={`${stance}label`} className="btn btn-outline-primary btn-sm" htmlFor={stance}>{stance}</label>
           </>
)}

Just to close this out I think the quickest/easiest solution was the following:

{["long", "short", "out", "none"].map(stance =>
           <React.Fragment key={stance}>
               <input type="radio" className="btn-check" id={stance} 
               autoComplete="off" checked={options.stance === stance} disabled={options.auto}/>
               <label className="btn btn-outline-primary btn-sm" htmlFor={stance}>{stance}</label>
           <React.Fragment/>
)}

CodePudding user response:

If you dont want to use a div just make a component that you can map and still keep the jsx like so.

function MyInput({stance}){
   return(
     <>
    <input type="radio" className="btn-check" id={stance} 
               autoComplete="off" checked={options.stance === stance} disabled={options.auto}/>
               <label className="btn btn-outline-primary btn-sm" htmlFor={stance}>{stance}</label>
    </> 
  )
}

Then for you map you can do this.

{["long", "short", "out", "none"].map((stance, i) =>
          <MyInput stance={stance} key={i}/>
)}

CodePudding user response:

Try this from the react documentation:

https://reactjs.org/docs/fragments.html#keyed-fragments

CodePudding user response:

 {["long", "short", "out", "none"].map((stance,index) =>
       <>
           <input type="radio" className="btn-check" id={stance} key={index}
           autoComplete="off" checked={options.stance === stance} disabled={options.auto}/>
           <label key={`${stance}label`} className="btn btn-outline-primary btn-sm" htmlFor={stance}>{stance}</label>
       </>

)}

in key use index instead of stance ,the index will come from map(stance,index)

  • Related