Posts > useForm

useForm

If you’ve been doing ReactJS for some time you know that it’s a lot of work just to do <Forms /> in React. There’s just too much stuff you have to do and consider. You have to do your own state management for the inputs else it’ll not work.

Here’s how I do it useForm method/hooks for creating Forms and this is my go-to custom hook for my forms.

import { useState, useEffect } from 'react';

export default function useForm(initial = {}) {
  // create a state object for our inputs
  const [inputs, setInputs] = useState(initial);

  const initialValue = Object.values(initial).join('');

  useEffect(() => {
    // this function runs when the things we are watching change
    setInputs(initial);
  }, [initialValue]);

  function handleChange(e) {
    let { value, name, type } = e.target;
    if (type === 'number') {
      value = parseInt(value);
    }
    if (type === 'file') {
      [value] = e.target.files;
    }
    if (type === 'checkbox') {
      const { checked } = e.target;
      value = checked;
    }
    setInputs({
      // copy the existing state
      ...inputs,
      [name]: value,
    });
  }

  function resetForm() {
    setInputs(initial);
  }

  function clearForm() {
    const blankState = Object.fromEntries(
      Object.entries(inputs).map(([key, value]) => [key, ''])
    );
    setInputs(blankState);
  }

  // return the thins we want to surface from this custom hook
  return { inputs, handleChange, resetForm, clearForm };
}

How will I use this on my form component? you just have to import the custom hook useForm , then pass initial data values.

const {inputs, handleChange} = useForm({ 
//add your initial values. you set it blank be blank as initial value too!
  name: 'Owa',
  age: 21,
  isCool: true,
})
...
<form>
	<labe>
	Name:
	<input type="textbox" name="name" onChange={handleChange} />
	</label>
	<label>
	Age:
	<input type="number" name="age" onChange={handleChange} />
	</label>
	...
</form>
👌Found this great library to use react-use-forms for much more complex forms that you need to build. Documentation is solid and easy to use. 👍

Tags 🏷