0

I want to clear input fields after clicking the submit button. I have used event.target.reset(); But it's not working. I have used React bootstrap form to get input values. Does any solution please? Check below my code.

const addItem = (event) => {
    event.preventDefault();
    const email = emailRef.current.value;
    const name = nameRef.current.value;
    const price = priceRef.current.value;

    const data = {email, name, price, quantity, description, supplier_name, img }
    const url = (`http://localhost:5000/myitems`);

    axios.post(url, data)
    .then(response =>{
        const {data} = response;
        if(data.insertedId){
            toast('Your Item Added!');
            event.target.reset();
        }
    })

}
return (
    <div className='container mx-auto w-50'>
        <h2 className='text-center my-3'>Add New Items</h2>
        <div className=''>
            <Form>
                <Form.Group className="mb-3" controlId="formBasicEmail">
                    <Form.Control ref={emailRef} type="email" value={user?.email} placeholder="Enter email" disabled/>
                </Form.Group>

                <Form.Group className="mb-3">
                    <Form.Control ref={nameRef} type="text" placeholder="Product Title" required/>
                </Form.Group>

                <Form.Group className="mb-3">
                    <Form.Control ref={priceRef} type="number" placeholder="Price" required/>
                </Form.Group>

                <Button onClick={addItem} variant="primary" type="submit">
                    Add Item
                </Button>
            </Form>
        </div>
    </div>
);

};

export default AddItem;

1 Answers1

0

Give the form an id. Then get the id of the form and run the reset() method.

document.getElementById("form-id").reset()

Also, you can give the form a ref. Then call the method current.reset()

const formRef = useRef(null);

<!-- your form -->
<form ref={formRef}>
...
</form>

Finally in your addItem() method, you can call the form ref to clear the form values.

formRef.current.reset()