Home > Back-end >  want to change input background color if not input not validated using useForm from react-hook-form
want to change input background color if not input not validated using useForm from react-hook-form

Time:07-10

I'm trying to validate a simple form using react-hook-form. I'm handling the validation part fine, the only problem I have at the moment is that I want to change the background color of the input field and at the same time add a little popup text if the field is not validated. I'm able to do the text popup part pretty easily, but can't seem to find a way to change the background color of the input. I was just wondering how it is possible to have a P tag inside the {errors} method and also to set a certain state in the same method. for example, If I want only the text popup, I can use the following :

<input name="name" {...register("name",{required:true}}/>
{errors.name && <p>Type a name</p>}

But how can I handle setting a state inside that method? for example, if I have a state :

const [background, setBackground] = useState(false);

How should I approach using the setBackground, something similar to this :

{errors.name && <p>Type a name</p> && {setBackground(true)}}

The following doesn't work, console says I'm rendering too much, but I'm curious If there's a solution similar to that. Would appreciate any advice! Here's the codesandbox link to better understand what I'm trying to achieve : https://codesandbox.io/s/aged-lake-ieyctq?file=/src/App.js

CodePudding user response:

You can achieve it via using the useEffect hook from react that will run your setBackground function if an error on the name field was detected:

useEffect(() => {
  if (errors.name) {
    setBackground(true); // sets background in case there was an error
  } else {
    setBackground(false); // unsets background in case there is no error
  }
}, [errors.name]);

See it working on your forked sandbox: https://codesandbox.io/s/mystifying-nobel-tpc0ee

  • Related