Home > front end >  React: use Children.map to edit props and use functions as Children in the same time
React: use Children.map to edit props and use functions as Children in the same time

Time:05-02

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',
        });
      })}

So how we can do if we want to use both (functional children, edit children props) in the same time? please !

CodePudding user response:

Assuming React.Children.map is present inside Example component, You can call the children from child's props if its a function with the arguments you want to pass or return the children.

{
  Children.map(children, (child, i) => {
    const _children = child.props.children 

    return cloneElement(child as ReactElement<any>, {
     children: typeof _children === "function" ? _children({parm1: "coucou"}) : children
    });
  })
}

CodePudding user response:

Thank you @Shan for helping me in your answer now you pass param1 for each children but what 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

  • Related