Reputation: 2978
I'm building a React Component for rendering an HTML form and I'm finding the need to recursively iterate through all children of my parent Form component in order to add extra props to only children components of a certain Type.
An example (in JSX):
<Form>
<p>Personal Information</p>
<Input name="first_name" />
<Input name="last_name" />
<Input name="email" />
<Label>
Enter Your Birthday
<Input name="birthday" type="date" />
</Label>
</Form>
In this example, I'm using React.Children.map inside my Form component, and then inside the map function I'm checking the child's "type" and the child's "type.displayName" to determine what element I'm dealing with (either a native HTML element or a ReactElement):
var newChildren = React.Children.map(this.props.children, function(child) {
if (is.inArray(child.type.displayName, supportedInputTypes)) {
var extraChildProps = {
alertColor: this.props.alertColor,
displayErrors: this.state.displayErrors
}
return React.cloneElement(child, extraChildProps);
} else {
return child;
}
}.bind(this));
My problem is that React.Children.map only shallowly iterates through this.props.children, and I would like it to also check children of children of children, etc. I need to add props to only my Input components so that they know when to display errors, and which color the error message should be displayed, etc. In the example above, the birthday input does not receive the necessary props, because it is wrapped in a Label component.
Any plan for React.Children.map to have a "recursive" mode or any other utility out there that can accomplish what I'm trying to do?
At the end of the day, I would like to write a single function that maps through each and every child (even nested ones) in order to perform an operation on it (in this case cloning).
Upvotes: 37
Views: 30997
Reputation: 76
in my case I write a recursive function which renders item of list and it's children
export const MenuCatalog: FC = () => {
return (
<div style = {{display: 'flex', flexDirection: 'column'}>
{recursive(testMenuData)}
</div>
)
}
my nested array:
const testMenuData = [
{
name: '1',
children: []
},
{
name: '1',
children: [
{
name: 'sub 1',
children: []
},
{
name: 'sub 2',
children: []
},
{
name: 'sub 3',
children: [
{
name: 'sub sub 1',
children: []
},
{
name: 'sub sub 2',
children: []
},
{
name: 'sub sub 3',
children: []
}
]
}
]
},
{
name: '3',
children: []
},
]
recursive function:
const recursive = (array: any, isChild?: boolean) => {
return (
array.map(item => (
<>
<CatalogMenuItem isChild = {isChild} name={item.name}/>
{item?.children.length ? recursive(item.children, true) : null }
</>
))
)
}
and custom component for render items:
export const CatalogMenuItem: FC<{name: string, isChild?: boolean}> = ({name, isChild}) => {
return (
<div className = {styles.cont} style = {isChild && {marginLeft: 10}}>{name}</div>
)
}
Upvotes: 0
Reputation: 871
My typescript version of the accepted answer.
const recursiveMap = (
children: ReactElement[],
fn: (child: ReactElement) => ReactElement
): ReactElement[] => {
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if ((child as ReactElement).props.children) {
const props = {
children: recursiveMap((child as ReactElement).props.children, fn)
}
child = React.cloneElement(child, props);
}
return fn(child);
});
}
Upvotes: 2
Reputation: 4660
While not baked into React, this is certainly possible:
import React from "react";
function recursiveMap(children, fn) {
return React.Children.map(children, child => {
if (!React.isValidElement(child)) {
return child;
}
if (child.props.children) {
child = React.cloneElement(child, {
children: recursiveMap(child.props.children, fn)
});
}
return fn(child);
});
}
If you'd like to avoid copy / pasting the above you can also use this npm package I authored.
Upvotes: 49
Reputation: 292
This thread actually misses the right answer:
const mapRecursive = (children, callback) => (
React.Children.map(
children,
child => (
child.props.children
? [callback(child), mapRecursive(child.props.children, callback)]
: callback(child)
),
)
);
Upvotes: 7
Reputation: 10453
I've made a small library to deal with the Children structure. You can check it here:
https://github.com/fernandopasik/react-children-utilities
In your case you can use the method deepMap:
import React from 'react';
import Children from 'react-children-utilities';
var newChildren = Children.deepMap(this.props.children, function(child) {
if (is.inArray(child.type.displayName, supportedInputTypes)) {
var extraChildProps = {
alertColor: this.props.alertColor,
displayErrors: this.state.displayErrors
}
return React.cloneElement(child, extraChildProps);
} else {
return child;
}
}.bind(this));
Upvotes: 8
Reputation: 108491
If you're looking to push props into a set of children under your component "automatically", you can also use context. This allows you to "give" properties, functions, etc. to child components by providing them from the parent with childContextTypes
and getChildContext()
, and having the child "request" them with contextTypes
.
Upvotes: 3
Reputation: 2978
Short answer to this is that its not currently possible as of React 0.14. As FakeRainBrigand mentioned, its more than likely a code smell anyway, so it should prompt a reevaluation of your implementation.
Upvotes: 1