Is there a way of adding props/attributes to children by looping over children
?
function Comp({ children }) {
children.forEach((child) => {
...
})
}
Is there a way of adding props/attributes to children by looping over children
?
function Comp({ children }) {
children.forEach((child) => {
...
})
}
2
Answers
You can do that. However, you shouldn’t use
.forEach
for that. What you need isChildren.map
andcloneElement
provided by React (and react-is package to check if child is React element).The type of
children
in React isReact.ReactNode
which is not necessarily an array, it could also be a primitive type like number, string or boolean, as well as a single React Element. (see its type in this response: https://stackoverflow.com/a/58123882/13167852).You need to make sure to account for these cases.
You can’t mutate props in React, including the special
children
prop, but you can create new components from them. You can do so with React’screateElement
function, which takes a component type ( a string) as first param (like"div"
,"button"
or"MyReactComponent"
), and a props object as second param. You can then spread the props of the child, and overwrite and/or add any other props you wantA (not complete) working example:
In this example, even though we passed
"asd"
forsomeProp
, that got overwritten to"foo"
insideComp
.