I am trying to fetch an array of JSON objects from the server and render the contents of each object dynamically-into a group of radio buttons.
In this example, I've got an array of 28 JSON objects, so I should see 29 radio buttons render (28 + 1 at the bottom of my code sample below) but they aren't rendering.
What am I missing?
export default function RadioButtonGroup({insurances, isLoaded}) {
if (!isLoaded) {
return (<h5>Loading...</h5>);
} else return(
<>
{
insurances.forEach((element) =>
<div id={`radioDiv_${element.id_in_group}`}>
<input type="radio" id={`button_${element.id_in_group}`} name="insGroup"/>
<label for={`button_${element.id_in_group}`}>{element.insurance_name}</label><br/>
</div>
)}
<input type="radio" id="notListed" name="insGroup"/>
<label for="notListed">My insurance is not listed.</label>
</>
);
}
The fetch works, and I have tested that I am getting an array of JavaScript objects out of the fetch, then passed as a prop to my function component (tested via console.log).
But when I view my component in the browser, the only radio button that appears is "My insurance is not listed", the radio button outside the dynamic radio button group.
your foreach()
is not returning anything as it just runs the function provided(which has no return method). I suggest using the map()
method instead, especially if you have an array of objects(json)
{insurances.map((element) => (
<div id={`radioDiv_${element.id_in_group}`}>
<input
type="radio"
id={`button_${element.id_in_group}`}
name="insGroup"
/>
<label for={`button_${element.id_in_group}`}>
{element.insurance_name}
</label>
<br />
</div>
))}
It is likely your object might have a slightly different object param names, it can be something as small as an accidental capital letter or missing a char etc. So make sure to double check the object being passed in has identical param names to the ones you are trying to extract.
If you have an object called MyObject and it has a format like this: {name:string, id:number}
If I tried console.log(MyObject.id)
there should be no error but if I accidentally typed: console.log(MyObject.Id)
then I will always get a null or undefined value because there is no param called 'Id', instead it should be 'id'.