Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using React.cloneElement() in JSX

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>
  )
}
}
like image 732
Kiran Avatar asked Feb 06 '18 12:02

Kiran


People also ask

When should I use React cloneElement?

React. cloneElement() is useful when you want to add or modify the props of a parent component's children while avoiding unnecessary duplicate code.

What is cloneElement in React?

cloneElement lets you create a new React element using another element as a starting point.

Can I use switch in JSX?

Did you know you can use switch statements in React (JSX)? This article explains how to go beyond the ternary operator and utilize switch statements in React. In a recent project, I needed conditional rendering beyond the binary option that ternary operators offer.

Can we use React with JSX?

React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.


1 Answers

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

like image 69
Shubham Khatri Avatar answered Oct 04 '22 19:10

Shubham Khatri