Skip to content

Instantly share code, notes, and snippets.

@mitchlloyd
Created July 14, 2017 16:58
Show Gist options
  • Save mitchlloyd/aca9f1773bd80707d4bb8066214fb462 to your computer and use it in GitHub Desktop.
Save mitchlloyd/aca9f1773bd80707d4bb8066214fb462 to your computer and use it in GitHub Desktop.
declarative react example
<script src="https://unpkg.com/[email protected]/dist/react.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.min.js"></script>
<title>React</title>
<div id="app"></div>
<script type="text/babel">
class App extends React.Component {
constructor() {
super();
this.state = { dogName: '', hasDog: null, output: null };
this.updateHasDog = this.updateHasDog.bind(this);
this.updateDogName = this.updateDogName.bind(this);
this.onSave = this.onSave.bind(this);
}
onSave() {
let formData = {
hasDog: this.state.hasDog,
dogName: this.state.dogName
};
this.setState({ output: JSON.stringify(formData) });
}
updateHasDog({ target }) {
this.setState({ hasDog: target.value === "yes" });
}
updateDogName({ target }) {
this.setState({ dogName: target.value });
}
isValid() {
return !this.state.hasDog ||
(this.state.hasDog && this.state.dogName);
}
render() {
return (
<div>
<p>Do you have a dog?</p>
<label>
<input onChange={this.updateHasDog}
name="hasDog"
type="radio"
value="yes" />{' '}
Yes
</label>
<label>
<input onChange={this.updateHasDog}
name="hasDog"
type="radio"
value="no" />{' '}
No
</label>
<br/><br/>
{this.state.hasDog && (
<div>
<label>What is the name of your dog?</label><br />
<input onChange={this.updateDogName} value={this.state.dogName} />
</div>
)}
<br/>
<button onClick={this.onSave} disabled={!this.isValid()}>Save</button>
<div>{this.state.output}</div>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment