Search code examples
javascriptreactjscomponentsjsx

React onChange method not working in login form


I'm facing this problem while trying to move input value to component state hook using the onChange attribute. i'll be happy with your help.

import React from 'react'
import { useState } from 'react';
import './userInterface.css';

function UserInterface() {

  const [userInfo, setUserInfo] = useState({
    isLoggedIn : '',
    userName : '',
    email : '',
    password : ''
  })


  let usenamePattern = /[A-Za-z0-9]{3,16}./ ;
  let emailPattern = /[A-Za-z0-9@.]{7,}/ ;
  
  
  const getInputToState = (e,inputField) => {
    
    
    
    switch(inputField){
      case 'username' : {
        setUserInfo(userInfo.userName = e.target.value) 
        console.log(userInfo)
        break
      }
      case 'email' : {
        setUserInfo(userInfo.email = e.target.value)
        console.log(userInfo)
        break
      }
      case 'password' : {
        setUserInfo(userInfo.password = e.target.value) 
        console.log(userInfo)
        break
      }
      default:
        return null
  
      }
      console.log(userInfo)

    
    
  }


  
  
  const alertForm = () => {


    if(userInfo.userName == '' && userInfo.email == '' && userInfo.password == ''){
      return{
        msg : '',
        color : 'green'
      }
    }
    
    else if(userInfo.userName.match(usenamePattern)){
      return {
        msg : 'You are allright !',
        color : 'limegreen'
      }
    }else if(!userInfo.userName.match(usenamePattern)){
      return {
        msg : 'Username should be more than 3 characters and less than 16, and contains only alphabets and numbers',
        color : 'red'
      }
    }

    
    
  }



  

  return (
    <div id='user-div'>
        <form id='user-form'>

            <h2 id="form-title">Tell us who you are :)</h2>

            <ul id="form-inputs">
              <li className="form-input">
                <input type="text" className="user-input" placeholder='Enter a username' maxLength={16} onChange={getInputToState()}/>          
              </li>
              <li className="form-input">
                <input type="text" className="user-input" placeholder='Enter your e-mail' onChange={getInputToState()}/>
              </li>
              <li className="form-input">
                <input type="text" className="user-input" placeholder='Create a password' onChange={(e) => {getInputToState()}}/>
              </li>
              <li className="form-input">
                <a><button className='action-form' id='submit-button' disabled>Submit</button></a>
              </li>
            </ul>

            <h4 id='alert-msg' style={{color : alertForm()?.color}}>{alertForm()?.msg}</h4>


            

            <h3 id='login-sign'>Already have an account ? <a href="/" id='login-form'>Log In</a></h3>
            
        </form>
    </div>
  )
}

export default UserInterface ;

here is the entire component code, it has no relation with props or exports. When i write in inputs the console returns nothing which means that the function do not work


Solution

  • The first you should do is change

    onChange={(e) => {getInputToState()}}

    to

    onChange={(e) => {() => getInputToState( e, 'your_field_name' )}}

    And inside your getInputToState function you should pass to setUserInfo new userInfo object with mutated fields or one field. Hope this will help.

    Your function should look like this:

    const getInputToState = (e, inputField) =>
    {
      const newUserInfo = userInfo; // create new state object
    
      userInfo[inputField] = e.target.value; // Change th value
    
      setUserInfo(newUserInfo); // Set new state
    
    };
    

    You also can get rid of the switch statement.