0

I am using React Hooks in my project and need trying to work out how to dynamically add a class to a className if the value of the state changes. I am using react-hook-form for validating my form.

RegisterForm.jsx

<input
  className={styles.authoriseInput}
  placeholder="Email"
  name="email"
  ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too long for this question
/>
{errors.email &&
  <p className={styles.errors}>Please enter a valid email.</p>
}

The second part works correctly and when there is an err, the <p> tag is shown. But I am stuck on how to update the input's className property in the same sort of manner. I want to add a style to authoriseInput that sets the border-color when error.email is triggered.

Any advice is greatly appreciated.

Thanks!

intRG
  • 45
  • 11

2 Answers2

4

Add a conditional to the clasName prop

<input
   className={errors.email ? styles.errorInput : styles.authoriseInput}
   placeholder="Email"
   name="email"
   ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too 
   long for this question
/>
{errors.email &&
    <p className={styles.errors}>Please enter a valid email.</p>
}
Moshe Sommers
  • 1,466
  • 7
  • 11
1

You can conditionally set classNames in the same way you would render component parts.

<input
  className={errors.email && styles.authoriseInput}
  placeholder="Email"
  name="email"
  ref={register({required: true, minLength: 4})}  # supposed to be a regex, but too long for this question
/>
{errors.email &&
  <p className={styles.errors}>Please enter a valid email.</p>
}
  • This will just result in undefined if error.email is false – Moshe Sommers Jun 18 '20 at 17:58
  • I agree, it depends on your expected result. If you want to achieve a class addition I always prefer `className={[styles.authoriseInput, errors.email && styles.errorInput]}` as discussed in https://stackoverflow.com/a/40824714/13745258. On this way, you inherit the base input style and only extend by error styles – sebastian-ruehmann Jun 18 '20 at 18:04
  • So the expected result is that the input will maintain its current styling, but will get a red border around it (imagine an invalid input on any website for login). What @sebastian suggested ends up with an error as it is always false, and what you mentioned above didn't style the input at all. I will keep playing around. – intRG Jun 18 '20 at 18:15
  • @intRG that's odd. What is the value of `styles.authoriseInput`. Are you eventually mixing up the use of `Stylesheet` and `ClassNames`? – sebastian-ruehmann Jun 18 '20 at 18:17
  • @sebastian I updated the question for clarification – intRG Jun 18 '20 at 18:26
  • WHOOPS THIS IS MY FAULT I SEE IT. I have border set to None in the error, I assume once that is removed it will work fine. Thanks! – intRG Jun 18 '20 at 18:28