Skip to content

Instantly share code, notes, and snippets.

@kristian76
Created October 2, 2017 06:59
Show Gist options
  • Save kristian76/b7628a2aa1756a8271747de96f2e9b1e to your computer and use it in GitHub Desktop.
Save kristian76/b7628a2aa1756a8271747de96f2e9b1e to your computer and use it in GitHub Desktop.
React JS app for search dictionary feature
/**
*
*
*/
import { render } from 'react-dom';
import React from 'react';
class SearchDictionaryFieldsComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
term: '',
hits: '',
site_id: '',
synonym: ''
};
this.handleSave = this.handleSave.bind(this);
this.handleChange = this.handleChange.bind(this);
}
/** Pass state to onSave via props */
handleSave() {
this.props.onSave(this.state);
}
/** Update component state onChange */
handleChange(e) {
let k = e.target.name,
v = e.target.value,
s = this.state;
s[k] = v;
this.setState(s);
}
componentDidMount() {
this.setState(this.props.fields);
}
render() {
return <div className="row">
<div className="col-md-3 form-group">
<label className="control-label">Term</label>
<input type="text"
className="form-control"
name="term"
value={ this.state.term }
disabled="true" />
</div>
<div className="col-md-3">{ this.state.hits }</div>
<div className="col-md-3 form-group">
<label className="control-label">Synonym</label>
<input type="text"
className="form-control"
name="synonym"
value={ this.state.synonym }
onChange={this.handleChange } />
</div>
<div className="col-md-3">
<button type="button"
className="btn btn-success"
onClick={ this.handleSave }>Save</button>
</div>
</div>
}
}
class SearchDictionaryFormComponent extends React.Component {
/** Pass data to onUpdate via props */
onSave(data) {
this.props.onUpdate(data);
}
render() {
let fields = this.props.dictionary.map((f, i) =>
<SearchDictionaryFieldsComponent
fields={ f }
key={ i }
onSave={ this.onSave.bind(this) } />
);
return <form>
{ fields }
</form>
}
}
class SearchDictionaryContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
dictionary: []
};
}
/** Post request to backend */
updateDictionary(dict) {
console.log(dict);
}
componentDidMount() {
/** Get request to fetch data from backend */
let dictionary = [
{
term: 'ace 16',
site_id: 16,
hits: 5,
synonym: ''
},
{
term: 'manchester city kruse',
hits: 10,
site_id: 16,
synonym: ''
},
{
term: 'arsenal caps',
hits: 5,
site_id: 16,
synonym: ''
},
];
this.setState({ dictionary: dictionary });
}
render() {
return <div>
<SearchDictionaryFormComponent
onUpdate={ this.updateDictionary }
dictionary={ this.state.dictionary } />
</div>
}
}
render(
<SearchDictionaryContainer />,
document.getElementById('app')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment