Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I can't catch the value of the checkbox input

I have a React form where I can’t control the value of the checkbox input with the useState hook. I don’t have this problem with other inputs.

I can’t pass the checkbox input value to the AuthData object. When you click the "Sign in" button, the console should display an AuthData object with the fields { login: ”, password: ”, isRemember: ” }

import React from 'react'
import { useState } from 'react'

export const AuthForm = ({ handlers }) => {
  const [authData, setAuthData] = useState({ login: '', password: '', isRemember: '' })

  const changeValue = (event) => {
    const { id, value } = event.target
    setAuthData((prevAuthData) => ({ ...prevAuthData, [id]: value }))
  }

  const signIn = () => {
    console.log(authData)
  }

  return (
    <form onSubmit={(e) => e.preventDefault()}>
      <input 
        type="text" 
        id="login" 
        placeholder="Login/E-mail/Phone" 
        value={authData.login} 
        onChange={changeValue} 
      />
      <input 
        type="password" 
        id="password" 
        placeholder="Password" 
        value={authData.password} 
        onChange={changeValue} 
      />
      <input 
        type="checkbox" 
        id="isRemember" 
        value={authData.isRemember} 
        onChange={changeValue} 
      />
      <button onClick={signIn}>Sign in</button>
    </form>
  )
}

When you change inputs values, their values must be passed to the authValue object.
With "login" and "password" inputs their values go into the authValue object, but with "isRemember" input this does not work. The value of checkbox inputs somehow does not get into the authValue object.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can check the input type and get the checked value for checkbox from the event object as below

const changeValue = (event) => {
  let { id, value, type, checked="" } = event.target;
  if (type === "checkbox") {
    value = checked;
  }
  setAuthData((prevAuthData) => ({ ...prevAuthData, [id]: value }));
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading