DEV Community

Discussion on: Forms in React

Collapse
 
arthurp93 profile image
Michael Marc-Arthur PIERRE

A link so i can learn more about this other approach please?

Collapse
 
kitsunekyo profile image
Alex Spieslechner

a simple example, to get you started

const [formState, setFormState] = useState();

const handleChange = (event) => {
  setFormState(previousState => ({
    ...previousState,
    [event.target.name]: event.target.value
  }));
}
Enter fullscreen mode Exit fullscreen mode

this will allow you to implicitly handle change for any form input, via its name attribute.
note that for fields that dont use value (like checkboxes) you'll have to do some more handling

you can also pass in a default state to the useState, or type it in typescript like that.

type FormState = {
  name: string;
  address: string;
}
const [formState, setFormState] = useState<FormState>(defaultState)
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
arthurp93 profile image
Michael Marc-Arthur PIERRE

Aw ok thanks for replied