13

I want to know how to use cloneElement syntax in JSX. I read Docs and tried examples but still don't have any clue.

class ABC extends React.Component {
  constructor(props){
    super(props)
}
render() {
  return(
  <div>
    {React.cloneElement()}
  </div>
  )
}
}
3

1 Answer 1

15

According to the documentation:

Clone and return a new React element using element as the starting point. The resulting element will have the original element’s props with the new props merged in shallowly. New children will replace existing children. key and ref from the original element will be preserved.

A valid use case for cloneElement is when you wish to add one/more props to the elements passed a children by the parent.You would simply map over all the children and clone them by adding new props for instance.

return (
  <div style={styles}>
    {React.Children.map(children, child => {
      console.log(child);
      return React.cloneElement(child, {newProp}, null);
    })}
  </div>
)

Check a working demo

Sign up to request clarification or add additional context in comments.

2 Comments

Should you please explain where you get child in React.Children.map?
In the above example children comes from props.children. child is a param passed to an arrow function. In ES5: jsx {React.Children.map(children, function(child){ console.log(child); return React.cloneElement(child, {newProp}, null); })} reactjs.org/docs/react-api.html#reactchildrenmap

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.