Fijir Fijir - 3 months ago 45
React JSX Question

Unknown Prop Warning

I'm getting an error when I work with children with props

Unknown prop
close
on <h3> tag. Remove this prop from the element.
.

I created a parent block:

var Block = React.createClass({
getInitialState: function() {
return {open: true}
},

close: function() {
this.setState({open: false});
},

render: function() {
var childrenWithProps = React.Children.map(this.props.children, function(child) {
return React.cloneElement(child, {
close: this.close
})
}.bind(this));

return (
<div>
{childrenWithProps}
</div>
)
}
});


And use it in another component:

var Elm = React.createClass({
render: function() {
return (
<Block>
<h3>Hi</h3>
<button type="button" onClick={this.props.close}>Close</button>
</Block>
)
}
});


I know it's because
<h3>
doesn't have
close
, but
button
has it.

How can I fix it?

Thank you.

Answer

You're getting this error because you're mapping React.Children which internally iterates the Block component's children (including the <h3> tag) and then assigns the close property to it.

Why you should pay attention to this warning.

But notice that neither <h3> nor <button> has the close property, what <button> has instead is the this.prop.close value passed as the onClick property.

What you can do then is to set some attribute to serve as a flag to your Block component so you can treat it like a "close element", let's call it closeEmitter:

Block.render()

var self = this;

var childrenWithProps = React.Children.map(function(child) {
  let extension = child.props.closeEmitter ? { onClick: self.close } : {}
  React.cloneElement(child, extension);
});

return <div>
  { childrenWithProps }
</div>

Elm.js

var Elm = React.createClass({
  render: function() {
    return <Block>
      <h3>Hi</h3>
      <button type="button" closeEmitter={ true }>Close</button>
    </Block>
  }
});
Comments