Skip to content

Instantly share code, notes, and snippets.

@lmbuffetti
Forked from rippo/dropdown.change.jsx
Created September 29, 2016 22:08
Show Gist options
  • Save lmbuffetti/b27865bf9ba73c80e8c3bb2de87f73e5 to your computer and use it in GitHub Desktop.
Save lmbuffetti/b27865bf9ba73c80e8c3bb2de87f73e5 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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment