Skip to content

Instantly share code, notes, and snippets.

@zcaceres
Created March 29, 2017 21:54
Show Gist options
  • Save zcaceres/3fd6c13d519ef125c3ecba013e6782cf to your computer and use it in GitHub Desktop.
Save zcaceres/3fd6c13d519ef125c3ecba013e6782cf to your computer and use it in GitHub Desktop.
FSA 1702, March 29, 2017

React & Forms

FSA 1702, March 29, 2017

"Do what you got to do." Because form logic sucks.


Forms

Validation gets really complicated really fast. All sorts of crazy edge cases that create spaghetti.

React to the rescue.

Declarative Forms

We can pass in the form's state. The form renders predictably from those inputs.

React can use event objects as well (React synthetic event).

  • These events don't persistent on their own because they are pooled

Controlled form components have their values directly controlled by the state. Much easier to manage.

Uncontrolled form components do not. No this.state for management. Harder.

Where does our form state belong?

Whatever needs our data, of course. Typically a 'smart container component'. Dumb components contain no state, they just render.

App vs. Local State

Depends on who needs access to the data.

<AppContainer>  // this.state = user: {}, favoriteDog: ''}
   /        \
<kittens> <puppies>
                \
                <FavPuppyFormContainer>
                    \
                    <FavPuppyForm> //has input

Example of an input

<input onChange={event => {
    this.setState({
      inputTitle: event.target.value
    }
  })}
type="text" />

<textarea style={{backgroundColor: this.state.inputColor}}onChange={event => {
  this.setState({
    inputEntryText: event.target.value
  });
}} />

<button onClick={() =>
  axios.post('/api/diary', {
    title: this.state.inputTitle,
    color: this.state.inputColor,
    text: this.state.inputEntryText
  })
  .then(function(response) {
    console.log(response.data);
  });
}/>

localStorage can be used to store data locally in the browser.

localStorage.getItem() localStorage.setItem()


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment