Jessie Richardson Jessie Richardson - 2 months ago 12
React JSX Question

Passing Keys As Props in Reactjs

I am trying to update the states of baseballIndex and footballIndex so that they can hold state independently without having to make an extra component. For example, when I change the footballIndex, I don't want the baseballIndex to change with it.

The problem is, when I pass props, the child component can only update the property of the key, but not the key itself.

Code is below and here is a link to the JSFiddle: https://jsfiddle.net/reactjs/69z2wepo/

var Home = React.createClass({
getInitialState: function() {
return {
baseballIndex: 0,
footballIndex: 0
};
},

increaseIndex: function(index) {
this.setState({index: this.state.index +1})
},

render: function() {
return <div>
<Tut sport={'Basbeall'}
index={this.state.baseballIndex}
increaseIndex={this.increaseIndex}/>
<Tut sport={'Football'}
index={this.state.footballIndex}
increaseIndex={this.increaseIndex}/>
</div>
}
});

var Tut = React.createClass({
render: function() {
return <div>
<div>
{this.props.sport}:
{this.props.index}
</div>
<div style={{width: 30, height: 30, backgroundColor: 'red'}}
onClick={()=> {this.props.increaseIndex(this.props.index)}}>
</div>
</div>;
}
});

ReactDOM.render(
<Home/>,
document.getElementById('container')
);

Answer

Try passing the sport ('baseball' or 'football') to the increaseIndex function instead of the index. For example in <Tut>:

var Tut = React.createClass({
render: function() {
    return <div>
             <div>
                 {this.props.sport}:  
                 {this.props.index}
             </div>
             <div style={{width: 30, height: 30, backgroundColor: 'red'}} 
                  onClick={()=> {this.props.increaseIndex(this.props.sport)}}> <--- Change this!
             </div>
           </div>;
  }
});

Then modify your increaseIndex function:

  increaseIndex: function(sport) {
    var stateKey = sport.toLowerCase() + 'Index';  // transform into your state's key
    var newState = this.state;  // copy the current state
    newState[stateKey] = newState[stateKey] + 1 // increment the state with specific index
    this.setState(newState)  // update the state
  },

It should update the appropriate state. You can also use anonymous functions although they will hurt performance in the case of many children.

Here's a fiddle: https://jsfiddle.net/69z2wepo/57095/