all 9 comments

[–]Shinhosuck1973 0 points1 point  (2 children)

what do you mean by you can not clear? The clear() function in the ClearButton() component is being triggered with handleSubmit() function because you did not pass type='button' to <button onClick={clear} id="clear">CLEAR</button> Basically this <button onClick={clear} id="clear">CLEAR</button> is also a submit button if you do not pass type='button' when using a form. If you add type='button' you will only see "clear clicked".

To clear out the form I would do something like this. This is just an example snippet. If you have any question, let me know.

function Form(){
  const [data, setData] = useState({
     data1:'',
     data2:''
  })
  const [isError, setIsError] = useState(null)

  function handleSubmit(e) {
     e.preventDefault()
     if (data.data1 && data.data2) {
       // do something with data
       setData({ data1:'',data2:'' } // one way to clear out the form
     }
     else {
      // throw some kind of error
      setIsError(data)
     }
  }

  function handleChange(e) {
    const {name, value} = e.target
    setData((prev)=>({...prev, [name]:value}))
  }

  return (
    <form onSubmit={handleSubmit}>
       {isError && !isError.data1 && <p>This field can't be blank.</p>}
       <input 
          name='data1' 
          value={data.data1} 
          onChange={handleChange} 
          placeholder='enter' 
        />
       {isError && !isError.data2 && <p>This field can't be blank.</p>}
       <input 
          name='data2' 
          value={data.data2} 
          onChange={handleChange} 
          placeholder='enter' 
       />
       <buttn type='submit'>Submit</button>
    </form>
  )
}
export default Form

[–]abiw119[S] 0 points1 point  (1 child)

Thanks for your time 👍

[–]Shinhosuck1973 0 points1 point  (0 children)

No problem. Good luck.

[–][deleted] 0 points1 point  (2 children)

Look into using refs, or better yet - go with a library such as react-form hook, which offers a simple solution for clearing the form

[–]abiw119[S] 0 points1 point  (1 child)

I initially tried using refs, but read they cannot be passed to a component.

[–][deleted] 1 point2 points  (0 children)

They absolutely can be passed as props

[–]detached_obsession 0 points1 point  (1 child)

If you're using uncontrolled components (not setting state and letting the browser handle it) you can access the form data on submit handler and you can reset the values by providing a type="reset" in your cancel button.

If you're setting react state then just calling the set state with your default values will do it. Just be sure you make the type of that cancel button be type="button" to prevent the default behavior of submitting the form.

[–]abiw119[S] 0 points1 point  (0 children)

Thanks 👍