ANP ANP - 2 months ago 16
React JSX Question

How to populate one drop down list from another

I have written teh following component to generate two dropdown where the

dllProducts
depends on
ddlCategories
but the issue is when passed the selected product category value to the function() getDataById it wont receive so i removed the code. in the function
ddlPordCatsChanegeEvent()
i have added a comment. Is this the right place to call the function
getDataById()
if not what is the proper way of doing generating the
ddlProducts


var gdata=[];

var trStyle = {
'color': 'black',
'border-style' :'solid',
'margin-left':'20%'
};

var TWODROPDOWNCOMP = React.createClass({
getInitialState:function(){
return{data1:[], data2:[], isMounted:false, selectedValue:0}
},
componentDidMount:function(){
this.getData();
this.setState({isMounted:true})
},
ddlProdCatsChanegeEvent: function(e) {

if (this.state.isMounted)
{
var newV = ReactDOM.findDOMNode(this.refs.refProdCats).value;
var seleValue = newV;

this.setState({selectedValue:newV}, function(){
alert(this.state.selectedValue);

//HOW DO I POPULATE THE OTHER DROPDOWN WITH ID ddlProducts using the child component PRODOPTIONS
});

}
},
render: function() {
var prodCats = this.state.data1.map(function(ele, index){
return <PRODCATSOPTION optValue={ele.ProductCategoryID} optText={ele.Name} />
});

prodCats.unshift(<PRODCATSOPTION optValue={''} optText={'--- select category ----'} />)

return (<div>Prodcut Category:<br /><select id="ddlCategories" ref="refProdCats" onChange={this.ddlProdCatsChanegeEvent}>{prodCats}</select><br />
Products:<br /><select id="ddlPorducts" ref="refProds"></select><br /></div>
)
},
getDataById:function(catId){
var x = catId;
alert('rec id:'+x);

$.ajax({
url:'http://localhost:33401/Home/GetProductCats?id='+ x,
method:'GET',
success:function(d1){
this.setState({data2:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
},
getData:function(){
//ajax here
$.ajax({
url:'http://localhost:33401/Home/GetProductCats',
method:'GET',
success:function(d1){
this.setState({data1:d1});
}.bind(this),
error:function(){
alert('ERROR');
}.bind(this)
})
}
});

var PRODOPTIONS = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}

});

var PRODCATSOPTION = React.createClass({
render:function(){
return(<option value={this.props.optValue}>{this.props.optText}</option> )
}

});




ReactDOM.render( <TWODROPDOWNCOMP/>, document.getElementById('d1') );

Answer

The select should be populated as you would normally do. After the AJAX call, the options come up.

<select id="ddlPorducts" ref="refProds">
  {this.state.data2.map(opt => (
    <option value={opt}>{opt}</option>
  ))}
</select>