Vaibhav
Vaibhav

Reputation: 485

Input value clear - React Hooks

I am trying to clear the input after the button click using useRef below is my code

After button click I cleared the state and the input value

    const [giftCode, setGiftCode] = useState('');
    const inputGift = useRef(null);
    const clickHandler = () =>{
       setGiftCode('');  
       inputGift.current.value = '';
     }

                        <TextInput
                            type="text"
                            field="gift-card-code"
                            ref={inputGift}
                            autoComplete="off"
                            onChange={event => {
                                setGiftCodeError(false);
                                setGiftBalanceCheck(null);
                                setGiftCode.bind(event.target.value);
                            }}
                        />

The input value is clearing, but the state showing the browser debugger is not changing, if we changed the input filed then the state is changing, useState setGiftcode is not changing the component actual state is there any alternate way to do this. see the below image for the understanding. enter image description here

Upvotes: 0

Views: 9249

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9779

You just need to define value as well to input fields to clear after submission.

<TextInput
 type="text"
 field="gift-card-code"
 ref={inputGift}
 value={giftCode}
 autoComplete="off"
 onChange={event => {
 setGiftCodeError(false);
 setGiftBalanceCheck(null);
 setGiftCode.bind(event.target.value);
 }}
/>

and just clear by defining as you have done already.

const clickHandler = () =>{
       setGiftCode(''); // this needs value attribute to input element for clearing 
     }

Upvotes: 0

crrmacarse
crrmacarse

Reputation: 1246

Why not instead of using ref. Assign your state as value in your input?

    const [giftCode, setGiftCode] = useState('');
    const clickHandler = () =>{
       setGiftCode('');  
     }

    ...
        <TextInput
             type="text"
             field="gift-card-code"
             value={giftCode} // this
             autoComplete="off"
             onChange={event => {
                    setGiftCodeError(false);
                    setGiftBalanceCheck(null);
                    setGiftCode.bind(event.target.value);
              }}
         />

Upvotes: 2

Related Questions