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.

import React, { useState } from 'react'

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

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

     [name]: value

  const handleSubmit = (e) => {

  return (
    <form onSubmit={handleSubmit}>
        <input type="text" name="username" onChange={handleChange} /></label>
        <input type="text" name="password" onChange={handleChange} /></label>
        <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/>

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

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.


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

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

Finally your 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'));