Created
June 20, 2017 22:09
-
-
Save brianlovin/72a88b0b14079496681567d800b5d9fc to your computer and use it in GitHub Desktop.
Set State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
export default class Test extends Component { | |
// if you're using flow or any sort of type checker, you can declar proptypes up here | |
state: { | |
value: string | |
} | |
// "The constructor method is a special method for creating and initializing an object created with a class." - MDN | |
constructor() { | |
super() | |
// set your initial state in the constructor | |
this.state = { | |
value: '' | |
} | |
} | |
onChange = (e) => { | |
e.preventDefault() | |
// a different way of setting state | |
const value = { | |
...this.state.value, | |
value: e.target.value | |
}; | |
this.setState({ value }); | |
} | |
render() { | |
// I like to extract props and state values before the return, but that's up to you | |
const { value } = this.state | |
return <input value={ value } onChange={ this.onChange } /> | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment