Skip to content

Instantly share code, notes, and snippets.

@rippo
Last active August 10, 2018 22:04
Show Gist options
  • Save rippo/370652886bb11e176908 to your computer and use it in GitHub Desktop.
Save rippo/370652886bb11e176908 to your computer and use it in GitHub Desktop.
ReactJS dropdown list example that gets data from a AJAX call with an on change event
var MyParentChange = React.createClass({
getInitialState: function() {
return {
data: [], value: {}, showOutput: false
}
},
componentDidMount: function() {
$.get(this.props.source, function(result) {
this.setState({
data: result
});
}.bind(this));
},
render: function() {
return (
<div onChange={this.changeHandler}>
<MySelectChange data={this.state.data} />
{ this.state.showOutput ? <MyOutputChange item={this.state.value}/> : null }
</div>
)
},
changeHandler: function(childComponent) {
this.state.data.forEach(function(item) {
if (parseInt(item.id) === parseInt(childComponent.target.value)) {
this.setState({ showOutput: item.id > 0 });
this.setState({ value : item});
}
}.bind(this));
}
});
var MyOutputChange = React.createClass({
render: function() {
return (<div>
<h3>Output</h3>
<p>Id: <b>{this.props.item.id}</b> Value: <b>{this.props.item.value}</b></p>
</div>)
}
});
var MySelectChange = React.createClass({
render: function() {
var mySelectOptions = function(result) {
return <MySelectOptionsChange
key={result.id}
data={result} />
};
return (
<select
className="form-control">
{this.props.data.map(mySelectOptions)}
</select>
)
}
});
var MySelectOptionsChange = React.createClass({
render: function() {
return <option value={this.props.data.id}>{this.props.data.value}</option>
}
});
React.render(
<MyParentChange source="/ajax/lookup" />,
document.getElementById('dropdownchange')
);
<div class="row">
<div class="col-md-4">
<p>Drop down from ajax wth change event</p>
<div id="dropdownchange"></div>
</div>
</div>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/JSXTransformer.js"></script>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.1/react.js"></script>
<script type="text/jsx" src="Dropdown.Ajax.Change.jsx"></script>
@VeeruSA
Copy link

VeeruSA commented Sep 25, 2017

I'm writing code in ReactJS.. I have 2 collections in my mongoDb named states and city. I want to create states and city dropdown lists so that if I select Any state then the if I click on city dropdown list, it shoud show only cities those are related to selected state.. Plz post ReactJs code for this..
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment