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

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

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 :

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

{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

>Solution :

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

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