MaG3Stican - Bryan Arbelo MaG3Stican - Bryan Arbelo - 4 months ago 13
Javascript Question

Extending child properties in parent throws read only exception

I am making an npm package to validate elements, I need to achieve the following syntax to be actually useful and easy :

<validationLibrary type="numeric">
<input type="text" placeholder"Sample 123">
</validationLibrary>


But my problem is with the child, the following throws an exception :

React.Children.map(this.props.children,function(child,i){
child.props.onChange = function (event) {
isNumeric(event.target.value);
}
})


My objective is for the library to force the child to execute the methods of my library it so the user doesnt have to do a millon configuration steps to get it working.

Any help?

EDIT :
Solution :

let copies = React.Children.map(this.props.children,(child,i) =>{
let copy = React.cloneElement(child,{onChange:function () {
console.log("i overrode the default behaviour");
}});
return copy;
})

return <div>{copies}</div>;

Answer

Since React v0.14, the props are frozen, it means you can't mutate them.

FMI: https://facebook.github.io/react/blog/2015/10/07/react-v0.14.html#breaking-changes

So, what you can do is, for each child, return a new element. In your case, you will clone the element and add a new prop to handle onChange. You can achieve that using React.cloneElement:

https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement

Comments