Skip to content

Instantly share code, notes, and snippets.

@Sergioamjr
Last active December 28, 2018 02:02
Show Gist options
  • Save Sergioamjr/315ae360d0cb139ecce2597496b38f13 to your computer and use it in GitHub Desktop.
Save Sergioamjr/315ae360d0cb139ecce2597496b38f13 to your computer and use it in GitHub Desktop.
useState example from React Hooks
import React, { useState } from "react";
function ComponentWithUseState() {
//states independentes
const [name, setName] = useState('');
const [age, setAge] = useState('');
//único state com várias propriedades
const [address, setAddress] = useState({street: '', city: ''})
const onChangeNameHandler = (event) => {
const {target: {value}} = event
setName(value)
}
const onChangeAgeHandler = (event) => {
const {target: {value}} = event
setAge(value)
}
const onChangeAddressHandler = (event) => {
const {target: {value, name}} = event
setAddress({...address, [name]: value})
}
return(
<form>
<input value={name} onChange={onChangeNameHandler} />
<input value={age} onChange={onChangeAgeHandler} />
<input value={address.street} name="street" onChange={onChangeAddressHandler} />
<input value={address.city} name="city" onChange={onChangeAddressHandler} />
</form>
)
}
export default ComponentWithUseState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment