Advertisement
Guest User

react-lifted-state-to-parent

a guest
Dec 28th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react'
  2.  
  3. /** Our Child Component text input */
  4. const CoolTextInput = ({ onChange, value }) => (
  5.   <input type='text' onChange={e => onChange(e.target.value)} value={value} />
  6. )
  7.  
  8. /** our React App */
  9. class App extends React.Component {
  10.   static FORM_FIELDS = {
  11.     TEXT_FIELDS: {
  12.       NAME: 'name',
  13.       AGE: 'age'
  14.     }
  15.   }
  16.  
  17.   /** All known keys */
  18.   static DEFAULT_STATE = {
  19.     [App.FORM_FIELDS.TEXT_FIELDS.NAME]: '',
  20.     [App.FORM_FIELDS.TEXT_FIELDS.AGE]: ''
  21.   }
  22.  
  23.   /** Set our initial state */
  24.   state = {...App.DEFAULT_STATE}
  25.  
  26.   /** When a text input changes, capture the change in state */
  27.   handleTextFieldUpdate = (field, value) => {
  28.     if (!this.state.hasOwnProperty(field)) {
  29.       return
  30.     }
  31.  
  32.     const newState = {
  33.       [field]: value
  34.     }
  35.  
  36.     this.setState(newState)
  37.   }
  38.  
  39.   /** Clear our form state */
  40.   clearForm = () => {
  41.     this.setState({ ...App.DEFAULT_STATE })
  42.   }
  43.  
  44.   render() {
  45.     const { FORM_FIELDS: { TEXT_FIELDS } } = App
  46.  
  47.     return (
  48.       <React.Fragment>
  49.         <h1>My App</h1>
  50.  
  51.         <h4>What is your name?</h4>
  52.         <CoolTextInput value={this.state[TEXT_FIELDS.NAME]} onChange={newValue => this.handleTextFieldUpdate(TEXT_FIELDS.NAME, newValue)} />
  53.  
  54.         <h4>What is your age?</h4>
  55.         <CoolTextInput value={this.state[TEXT_FIELDS.AGE]} onChange={newValue => this.handleTextFieldUpdate(TEXT_FIELDS.AGE, newValue)} />
  56.  
  57.         <div>
  58.           <button onClick={this.clearForm}>Clear Form</button>
  59.         </div>
  60.       </React.Fragment>
  61.     )
  62.   }
  63. }
  64.  
  65. export default App
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement