React-Hook-Form - adding icon inside input when form validation goes wrong

Viewed 579

I am trying to create form with react and already took care of most of the validations (like displaying the message). I would also like to add icon/img inside the input when it is invalid. What would be the best approach to this?

Also, how to reset inputs after submitting form?

import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';


function Form() {
    const { register, handleSubmit, formState: { errors } } = useForm();
    const onSubmit = (data) => {
        console.log(data)
    }
    const registerOptions = {
       
        email: {
            required: "Email cannot be empty",
            pattern: {
                value: /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/,
                message: "Looks like this is not an email"
            }
        }
    }
    return (
        <div className="form">
            <form onSubmit={handleSubmit(onSubmit)}>           
                <input
                    type="text"
                    placeholder='Email Address'
                    name="email"
                    {...register('email', (registerOptions.email)
                    )} />
                {errors.email && <p>{errors.email.message}</p>}               
                <input type="submit" value="Claim your free trial" className="submit" />             
            </form>
        </div>
    )
}

export default Form;
1 Answers

To reset the Input fields you could do this:

const onSubmit = (data, e) => {
        e.target.reset();
        console.log(data);
    }

If you want to add icons inside your inputs, I recommend you to search for bootstrap and https://www.npmjs.com/package/classnames

Related