Goal: I need to perform some post-processing of React components, and that involves removing some props. I tried to use React.cloneElement passing {propToRemove: undefined} as the second argument, but the prop is not removed, just set to undefined. I could use React.createElement, but according to the docs, that would lose refs, which is a serious drawback.
A contrived example not doing anything useful, just to test:
const removeUnknownPropWithClone = (el) => {
return React.cloneElement(el, {unknownProp: undefined})
};
const App = (props) =>
removeUnknownPropWithClone(
<div unknownProp="1">Hello</div>
);
This shows the error message: "React does not recognize the unknownProp prop on a DOM element". Indeed, the prop is set to undefined, but it's still there. I need to completely remove it.
Runnable snippet (open the console to see the error messages)
Related question (but not answered there): React - Remove prop from child
Relevant source code: https://github.com/facebook/react/blob/master/packages/react/src/ReactElement.js#L293
Very simple with JSX (inside a Children.map() function):
const { filtered, ...rest } = child.props
const clone = <child.type key={child.key} ref={child.ref} {...rest} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With