React Hooks/useState Form Example

Working with React Hooks is fun. In this code example, i’m basically going to show you how to create a form in functional components with useState. Also my form will include checkboxes.

//Form.js
import React, { useState } from 'react'

export const Form = () => {
  const [input, setInput] = useState({})

  const handleChange = (e) => { 
    let { name, value, type, checked } = e.target
     value = type === "checkbox" ? checked : value

    setInput({
    ...input,
     [name]: value
  })
  }

  const handleSubmit = (e) => {
      e.preventDefault()
      console.log(input)
  }

  return (
    <form onSubmit={handleSubmit}>
        <label>Username:
        <input type="text" name="username" onChange={handleChange} /></label>
        <br/>
        <label>Password:
        <input type="text" name="password" onChange={handleChange} /></label>
        <br/>
        <input type="checkbox" name="male" onChange={handleChange} />Male<br/>
        <input type="checkbox" name="female" onChange={handleChange} />Female<br/>
        <input type="checkbox" name="none"  onChange={handleChange} />None of these<br/>
      <button>Submit</button>
    </form>
  )
}

In handleChange function we are checking the type of input and if input is checkbox, we’re assigning event.target.checked to value variable instead of event.target.value

Its’a basic component example. So if you want to run this, you need to include it in your App. Here is a simple example to how to include it.

//App.js

import React from 'react'
import { Form } from './Form'

function App() {
  return ( <div><Form/></div> )
}

Finally your index.js

//index.js
//...your imports...
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
//..your imports...

ReactDOM.render(<App />, document.getElementById('root'));