Home > database >  How to activate button in condition
How to activate button in condition

Time:12-05

const Login= () =>
const [ID, setID] = useState();
const [PW, setPW] = useState();
function handleIdInput(event){
        setID(event.target.value);
        console.log(ID);
    }
    function handlePWInput(event){
        setPW(event.target.value);
        console.log(PW);
    }
                   <form>
                        <div>
                            <input type="text" id="ID" className='boxes'  onChange = {handleIdInput}  />
                        </div>
                        <div>
                            <input type="password" id="password" className='boxes'  onChange = {handlePWInput} />
                        </div>
                        
                        <button className='boxes' type='button' onClick={goList}>
                            LogIn
                        </button>
                        
                    </form>

I want to activate the button if id includes @ and password has at least 7 characters. I'm trying to find a way not to use class and this method. Thank you!

CodePudding user response:

Please make use of disabled property.

 <button className='boxes' type='button' onClick={goList} disabled={()=> checkDisabled(ID, PW)}>
   LogIn
 </button>

The checkDisabled function must return true or false based on your requirements.

const checkDisabled = (id, password) => {
 // condition here
 if(id.includes('@') && password.length >= 7)
 {
    return false;
 }
 
 return true;
}

Then finally the component code must look like this. Please note the changes I have made related to how the state variables are connected with the input component.

import { useState } from "react";

const Login = () => {
  const [ID, setID] = useState("");
  const [PW, setPW] = useState("");

  function handleIdInput(event) {
    setID(event.target.value);
    console.log(ID);
  }

  function handlePWInput(event) {
    setPW(event.target.value);
    console.log(PW);
  }

  const checkDisabled = (id, password) => {
    // condition here
    if (id.includes("@") && password.length >= 7) {
      return false;
    }
    return true;
  };

  return (
    <form>
      <div>
        <input
          type="text"
          id="ID"
          className="boxes"
          value={ID}
          onChange={(e) => handleIdInput(e)}
        />
      </div>
      <div>
        <input
          type="password"
          id="password"
          className="boxes"
          value={PW}
          onChange={(e) => handlePWInput(e)}
        />
      </div>

      <button
        className="boxes"
        type="button"
        onClick={goList}
        disabled={() => checkDisabled(ID, PW)}
      >
        LogIn
      </button>
    </form>
  );
};

export default Login;

Reference for useState hook.

  • Related