skip to Main Content

I can’t seem to get the button component here to enable after the input fields are filled, it simply starts disabled and then stays that way.

export default function Page() {
 const [newPassword, setNewPassword] = useState('');
 const [confirmPassword, setConfirmPassword] = useState('');
 const [isButtonDisabled, setIsButtonDisabled] = useState(true);


 useEffect(() => {
   setIsButtonDisabled(newPassword === '' || confirmPassword === '');
 }, [newPassword, confirmPassword])


 return (
   <>
     <Paper>
       <form
         onSubmit={(e) => {
           e.preventDefault();
           if (newPassword === confirmPassword) {
               console.log('Passwords match. Submitting form...');
             } else {
               console.log('Passwords do not match. Please try again.');
             }
         }}
         className="mb-0 mt-6 mb-6 space-y-4 rounded-lg p-4 shadow-lg sm:p-6 lg:p-8 bg-white"
       >
         <div className="text-center sm:text-left">
           <h1 className="text-2xl font-bold text-blue-900 sm:text-3xl">New Password</h1>
         </div>
         <div className="mb-4">
           <Input
               type="password"
               title="Enter New Password"
               value={newPassword}
               onChange={(e) => {
               setNewPassword(e.target.value);
               }}
           />
         </div>
         <div className="mb-6">
           <Input
               type="password"
               title="Confirm Password"
               value={confirmPassword}
               onChange={(e) => {
               setConfirmPassword(e.target.value);
               }}
           />
         </div>
         <div className="flex flex-col items-left space-y-4">
            <Button type="submit" disabled={isButtonDisabled} >
             Send
           </Button>
         </div>
       </form>
       <p className="text-center mt-6 text-gray-500 text-xs">&copy; 2024 Compass Center</p>
     </Paper>
   </>
 );
}

I changed my code around to utilize useEffect, thinking that would solve the issue, but it still does not work.

2

Answers


  1. you did not pay attention to this condition
    setIsButtonDisabled(newPassword === ” || confirmPassword === ” || newPassword !== confirmPassword);

    Login or Signup to reply.
  2. setIsButtonDisabled(newPassword === '' || confirmPassword === '');
    

    You set this in the useEffect, which monitors the two variables:

     }, [newPassword, confirmPassword])
    

    So if one of the two variables changes the setIsButtonDisabled is triggered.

    The problem is that if the newPassword is empty ” or the confirmPassword is emptythe button is disabled.

    But if they are not empty strings the button is abled.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search