Reputation: 687
I have found various questions regarding this error but unable to find the right solution.
I am trying to build a seriesradioInput
components to be part of a RadioGroup. I build this through a radioGroup
component which will pass down various properties to the inputs which it receives. When I map through the values of the object I get the following error:
Error: Objects are not valid as a React child (found: object with keys {radioInputs}). If you meant to render a collection of children, use an array instead.
How am I suppose to properly map through Object data and use values to pass into a component without them returning as objects?
import React from 'react';
import RadioInput from './radioInput';
export const RadioGroup= props => {
const courseTypes = {
type1: {
label: "Course A"
},
type2: {
label: "Course B"
}
}
const radioInputs = Object.values(courseTypes).map(data => {
return(
<RadioInput
disabled={false}
type={"radio"}
label={data.label}
/>
)
})
return(
{radioInputs}
)
}
export default RadioGroup
Upvotes: 1
Views: 3921
Reputation: 1506
Your returning an array of JSX Elements when react components expects one element as the return value. Simply wrapping you return in a fragment should fix this. Like so
return(
<>{radioInputs}</>
)
Just for the record as pointed out in the comments you can return an array of JSX.Element. So the following (without the curly braces) would also work.
return(radioInputs)
Upvotes: 3
Reputation: 13071
I think that you want to do this instead:
import React from 'react';
import RadioInput from './radioInput';
export const RadioGroup= props => {
const courseTypes = {
type1: {
label: "Course A"
},
type2: {
label: "Course B"
}
}
return Object.entries(courseTypes).map(([key, data]) => (
<RadioInput
key={key}
disabled={false}
type={"radio"}
label={data.label}
/>
))
}
export default RadioGroup
Explanation of changes:
Your code was inadvertently returning a plain JS Object. This version returns an array of JSX elements.
It uses Object.entries
, instead of Object.values
in order to access the key of each entry. The reason being that when you return an array, each entry must have a unique key.
Upvotes: 2