Skip to content

Instantly share code, notes, and snippets.

@developit
Forked from pk11/reactjs.js
Last active August 29, 2015 14:23
Show Gist options
  • Save developit/a9df71b32833563eb45f to your computer and use it in GitHub Desktop.
Save developit/a9df71b32833563eb45f to your computer and use it in GitHub Desktop.
/**
* Our component structure will look like the following:
* - WikiBox
* -- AutoCompleteBox
* --- AutoComplete
*/
/** Renders a single entity coming from wikipedia */
class AutoComplete extends React.Component {
render() {
return <p>{this.props.name}</p>;
}
}
/** Parent of AutoComplete */
class AutoCompleteBox extends React.Component {
render() {
let nodes = this.props.list.map( item => <AutoComplete name={item} /> );
return (
<div className="autocompleteNodes">{nodes.mutable()}</div>
);
}
});
/** Main component */
class WikiBox extends React.Component {
constructor(props) {
super(props);
this.state = {
autocomplete: immutable.array([]),
call: { latest:0, term:'' }
};
}
makeCall(term, current) {
let wikiUrl = `http://en.wikipedia.org/w/api.php?action=opensearch&format=json&callback=?&search=${encodeURIComponent(term)}`;
$.getJSON(wikiUrl, data => {
if (current == this.state.call.latest) {
let newPriority = this.state.call.latest - 1;
this.setState({
autocomplete: immutable.array(data[1]),
call: { latest: newPriority, term:'' }
});
}
});
}
handleKeyUp(e) {
let term = e.target.value;
if (term.length>3) {
let latest = this.state.call.latest+1;
this.setState({
call: { latest, term }
});
}
if (!term.length && this.state.autocomplete.length) {
this.setState({
autocomplete: immutable.array([]),
call: { latest:0, term:'' }
});
}
return false;
}
render() {
let { latest, term } = this.state.call || {};
// if the incoming state contains a search term with a real priority then make the async ajax/jsonp calls
if (latest && term) {
this.makeCall(term, latest);
}
return (
<div className="wikibox">
<span>Give it a try:</span>
<input type="text" placeholder="search" onKeyUp={this.handleKeyUp} />
<AutoCompleteBox list={this.state.autocomplete} />
</div>
);
}
}
React.renderComponent(
<WikiBox />,
document.getElementById('container')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment