React.cloneElement is a function that clones a React element and allows adding new props to it.
Simple analogy: Imagine you have a coloring book. You give a child a picture (React element). React.cloneElement — is to make a photocopy of the coloring book and add pre-drawn lines (add new props) to it. You get the same coloring book, but with changes.
How it works:
1function Parent({ children }) {2 return (3 <div>4 {React.Children.map(children, (child) =>5 React.cloneElement(child, { className: 'highlighted' })6 // Take each child and add className to it7 )}8 </div>9 );10}1112<Parent>13 <p>First paragraph</p> {/* Will get className='highlighted' */}14 <p>Second paragraph</p> {/* And this one too */}15</Parent>
React.Children — utilities for working with children:
React.Children.map(children, fn) — apply a function to each child.React.Children.count(children) — number of children.React.Children.toArray(children) — turn into an array (can sort, filter).React.Children.only(children) — check that there is only one child (otherwise error).When this is used: In libraries (Material UI, Ant Design) for modifying child components. For example, Tabs adds "active" class to the selected tab.
Important: