Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React from 'react'
- /** Our Child Component text input */
- const CoolTextInput = ({ onChange, value }) => (
- <input type='text' onChange={e => onChange(e.target.value)} value={value} />
- )
- /** our React App */
- class App extends React.Component {
- static FORM_FIELDS = {
- TEXT_FIELDS: {
- NAME: 'name',
- AGE: 'age'
- }
- }
- /** All known keys */
- static DEFAULT_STATE = {
- [App.FORM_FIELDS.TEXT_FIELDS.NAME]: '',
- [App.FORM_FIELDS.TEXT_FIELDS.AGE]: ''
- }
- /** Set our initial state */
- state = {...App.DEFAULT_STATE}
- /** When a text input changes, capture the change in state */
- handleTextFieldUpdate = (field, value) => {
- if (!this.state.hasOwnProperty(field)) {
- return
- }
- const newState = {
- [field]: value
- }
- this.setState(newState)
- }
- /** Clear our form state */
- clearForm = () => {
- this.setState({ ...App.DEFAULT_STATE })
- }
- render() {
- const { FORM_FIELDS: { TEXT_FIELDS } } = App
- return (
- <React.Fragment>
- <h1>My App</h1>
- <h4>What is your name?</h4>
- <CoolTextInput value={this.state[TEXT_FIELDS.NAME]} onChange={newValue => this.handleTextFieldUpdate(TEXT_FIELDS.NAME, newValue)} />
- <h4>What is your age?</h4>
- <CoolTextInput value={this.state[TEXT_FIELDS.AGE]} onChange={newValue => this.handleTextFieldUpdate(TEXT_FIELDS.AGE, newValue)} />
- <div>
- <button onClick={this.clearForm}>Clear Form</button>
- </div>
- </React.Fragment>
- )
- }
- }
- export default App
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement