We can use the `cloneElement` to extend the children components.
E.g.
- We have a `<App>` component which contain `<Buttons>` component.
- In below example we have `<Buttons>` component which have 3 buttons: A, B, and C.- In `<Buttons>` component we have state `selected`
- We have markup `<p>You have selected: {selected}</p>`.
- Initialy `selected` does not contain any value.
- We have added the `onClick` event for each childern `<button>` with the help of `cloneElement()` function.
- With `cloneElement()` we extend each `<button>` children.
- So, On click on any button we used `setSelected()` to set our current button value.
- And then we see:
- On click on `A` button – We see `<p>You have selected: A</p>`
- On click on `B` button – We see `<p>You have selected: B</p>`
- On click on `C` button – We see `<p>You have selected: C</p>`
import React, { useState, cloneElement } from 'react';
const Buttons = ( {children} ) => {
let [selected, setSelected] = useState('');
let buttons = children.map( child => {
return cloneElement( child, {
onClick: ( item ) => { setSelected( item.target.value ) }
})
} );
return (
<div>
<p>You have selected: {selected}</p>
{buttons}
</div>
)
}
const App = () => {
return (
<Buttons>
<button value="A">A</button>
<button value="B">B</button>
<button value="C">C</button>
</Buttons>
)
}
export default App;