I want to use Children.map to edit props for each child and use functions as Children to pass params in the same time
In React we can use Functions as Children Like that
children({param1: 'coco', param2: 'bibi'})
And so we use it Like that
<Example>
{({param1, param2}) => (<div>{param1}</div>)}
</Example>
And if we want to edit props for each child we use this method
{Children.map(children, (child, i) => {
return cloneElement(child as ReactElement<any>, {
param1: 'coucou',
});
})}
I want todo is like this in my situation
<Example>
{({param1, param2}) => data.map(item=> <ExampleChild> {item.text} {param1} </ExampleChild>)}
</Example>
I want this case and also i want to add props to ExampleChild from Example for example I want to pass a prop index to ExampleChild from Example directly
So how we can do if we want to use both (functional children, edit children props) in the same time? please !
If you want to add index to Example's child you should not use fragments which will be treated as a single child and .map won't work.
It should be in an array
export const Default = () => {
return <Example>{({param1}) => [<Test>{param1}</Test>, <Test>hello2</Test>]}</Example>;
};
You can pass index via cloneElement
function renderChildren() {
const _children = children({ param1: 'foo' });
return React.Children.map(_children, (child, idx) => {
return cloneElement(child, {
/* Add props here , if you want to passs it to ExampleChild */
index: idx,
});
});
}
Example.jsx
function Example({ children }) {
function renderChildren() {...}
return <div>{renderChildren()}</div>
}
iT works for me when i do like this
export const Parent = ({ children, ...rest }) => {
return <Box {...rest}>{children({ param1: 'fofo' })}</Box>;
};
export const ParentFragment = ({ children }) => {
return Children.map(children, (child, idx) => {
return cloneElement(child as ReactElement<any>, {
index: idx,
});
});
};
export const Test = ({ index, children }) => {
console.log({ index });
return <div>{children}</div>;
};
export const App = () => {
return (
<Parent>
{({param1}) => (
<ParentFragment>
<Test>hello {param1}</Test>
<Test>hello2</Test>
</ParentFragment>
)}
</Parent>
);
};