Sangit Dhanani Sangit Dhanani - 1 month ago 5
React JSX Question

Html tags renders but does't function in reactjs

I have a div which renders on a boolean condition triggered by a button.
I have multiple select options in the new div. The problem is just the first works and others dont.

Code Snippet:

var Results = React.createClass({
getInitialState: function(){
return {
partname:[],
moveOptions: false,
fromLocation:'',
toLocation:'',
moveQuantity:0
}
},
componentWillMount:function(){
var partInfo = [];
var count = 0;
//ajax calls to get partInfo
this.setState({
partInfo:partInfo
});
},
showMoveOptions: function(){
this.setState({moveOptions:!this.state.moveOptions});
},

movePart: function(){
//ajax call
},
handleQuantityChange: function(e){
this.setState({
moveQuantity:e.target.value
});
},
handleFromChange: function(e){
this.setState({
fromLocation:e.target.value
});
},
handleToChange: function(e){
this.setState({
toLocation:e.target.value
});
},

render: function() {
var partInfo = this.state.partInfo;
return(
<div>
<div id="results">
<br/>
<div className="col-sm-6">
<h3>Part Name :{this.props.partname}</h3>
<div className="container">
{
partInfo.map(function(l){
return([
<div>
<h3>Building: {l.building}</h3>
<h3>Location: {l.location}</h3>
<h3>Quantity: {l.qty}</h3>
</div>
]);
}.bind(this))
}
</div>
</div>
<div className="col-sm-6">
<button type="button" onClick={() => this.showMoveOptions()}>Move</button>

</div>
</div>
{ this.state.moveOptions ?
<div>
<div>
<h3>From: </h3>
<select onChange={this.handleFromChange.bind(this)}>

partInfo.map(function(from){
return(
<option value={from.location}>{from.location}</option>
)
}
</select><br/>
<h3>To: </h3>
<select onChange={this.handleToChange.bind(this)} >

partInfo.map(function(to){
return(
<option value={to.location}>{to.location}</option>
)
}
</select><br/>

<h3>Quantity:</h3>
<input type="text" name="quantity" value={this.state.moveQuantity} onChange={this.handleQuantityChange.bind(this)}/>

</div>
<div>
<button type="button" onClick={() => this.movePart()}>Submit</button>
</div>
</div> : null
}
</div>
);
}


});

As shown in the code the first select tag works. After that all tags are rendered but i neither can select the drop down menu nor i can change text in input tag.

Answer

You should handle onChange event to update controlled input.

Check the documentation here

A controlled <input> has a value prop. Rendering a controlled <input> will reflect the value of the value prop.

and

User input will have no effect on the rendered element

I've made a fiddle with your code. You have lost some brackets in your snippet, and you should not bind handlers to this when using React.createClass syntax. But the rest is working just fine.