I would like to add some props to my component using {React.cloneElement(<MyComponent />, { onClick: () => console.log('click'), style: {background: 'red'} })}
Full code:
const MyComponent = () => {
return (
<div>
foooo
</div>
);
};
....
return React.cloneElement(<MyComponent />, { onClick: () => console.log('click'), style: {background: 'red'} })
But props
are not passed into my component.
When I use:
return React.cloneElement(<div>foooo</div>, { onClick: () => console.log('click'), style: {background: 'red'} })
Props are working. Why? I don`t understand why.
Why would you use
cloneElement
when you got JSX available (can conclude it fromMyComponents
syntax).Instead do:
And fix your component:
JSX is sugar syntax for
createElement
/cloneElement
.React.cloneElement() is almost equivalent to:
Therefore the right syntax: