'Why does this code give an "Each child in a list should have a unique 'key' prop" error?
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/>
)}
Solution 1:[1]
Try this from the react documentation:
https://reactjs.org/docs/fragments.html#keyed-fragments
<React.Fragment key={your key}>
{your code}
</React.Fragment>
Solution 2:[2]
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}/>
)}
Solution 3:[3]
{["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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Matt |
| Solution 3 | mahmoud2020 |
