Ad

ReactJS - Passing Prop Value To Component Before Final ReactDOM.render()

- 1 answer

I want to pass a value to a component this way, but when I try to console log this.props.vouch it returns an undefined value. I know it will work if I put:

<Something onClick={this.log} vouch=this.props.vouch />

and

ReactDOM.render(<List vouch="value 1"/>, document.getElementById('react-app'))

But I will want to use different vouch value later in the code and be able to reuse Something component.

var Something = React.createClass({
 propTypes:{
    vouch: React.PropTypes.string,
},
    render: function() {
        return (
        <div>
            <h1 onClick={this.props.onClick} vouch={this.props.vouch}>Click!</h1>
        </div>
        );
    }
});
var List = React.createClass({

    log: function() {
        console.log(this.props.vouch);
    },
    render: function  () {
        return (
            <Something onClick={this.log} vouch="value 1" />
            <Something onClick={this.log} vouch="value 2" />
            );
    }
});
ReactDOM.render(<List />, document.getElementById('react-app'));
Ad

Answer

You can't set this.props from child component, but you can pass data using data attributes, like this

<h1 onClick={this.props.onClick} data-vouch={this.props.vouch}>Click!</h1>

...

log: function (e) {
    console.log(e.target.dataset.vouch);
},

Example

or using .bind, like this

<h1 onClick={this.props.onClick.bind(null, this.props.vouch)}>Click!</h1>

...

log: function (vouch) {
  console.log(vouch);
},

Example

or call callback in child component and pass props, like this

handleClick: function () {
  this.props.onClick(this.props.vouch)
},

render: function() {
  return (<div>
    <h1 onClick={this.handleClick}>Click!</h1>
  </div>)
}

...

log: function (vouch) {
  console.log(vouch);
},

Example

Ad
source: stackoverflow.com
Ad