Skip to content

Instantly share code, notes, and snippets.

@brianlovin
Created June 20, 2017 22:09
Show Gist options
  • Save brianlovin/72a88b0b14079496681567d800b5d9fc to your computer and use it in GitHub Desktop.
Save brianlovin/72a88b0b14079496681567d800b5d9fc to your computer and use it in GitHub Desktop.
Set State
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