DEV Community

Discussion on: Forms in React

Collapse
 
kitsunekyo profile image
Alex Spieslechner

life's easier if you just use a single state object for your whole form, and a changeHandler that uses es6 dynamic properties. the switch and custom useStates get annoying real quick.

not the best way to approach formstate

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

Collapse
 
eidorianavi profile image
EidorianAvi • Edited

Thanks for taking the time to read the article! I understand where you're coming from but opted for this approach purely by preference.

I appreciate your input.