Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify attributes of children in ReactJS component

Tags:

reactjs

I am trying to figure out how to modify the children of a component to for example, add a class. I have tried to do:

var inputReactObject = React.Children.only(this.props.children);

inputReactObject.className = "test";

However that does not seem to work.

Is it possible to modify children attributes in a ReactJS component?

Full plunker: http://plnkr.co/edit/msbUSDBQn17qXzBHzGXD?p=preview

like image 925
ryanzec Avatar asked Nov 11 '14 11:11

ryanzec


2 Answers

Now that cloneWithProps is deprecated, the current approach would be

var inputReactObject = React.Children.only(this.props.children);
var clonedChild = React.cloneElement(inputReactObject, {
  className: "input-element test"
});

return clonedChild;
like image 161
Josh Kelley Avatar answered Nov 12 '22 09:11

Josh Kelley


As mentioned by @lpiepiora plunker, the code to do what I want would be:

var inputReactObject = React.Children.only(this.props.children);
var clonnedChild = React.addons.cloneWithProps(inputReactObject, {
  className: "input-element test"
});

return clonnedChild;
like image 30
ryanzec Avatar answered Nov 12 '22 09:11

ryanzec