Home > Net >  How to clear input type text in Reactj
How to clear input type text in Reactj

Time:11-12

I am working in Reactjs and i am using nextjs,Right now i am trying to clear input field after click but not successful,Here is my code

<form onSubmit={handleSubmit}>
            <input
            type="text"
            name="name"
            id="name"
            placeholder="Type your email here"
            value={state.name}
            onChange={handleChange}
          />

      <button type="submit" className='btn-remindme'>Remind me </button></form>

And i tried with following code for clear input text

const [state, setState] = useState({
    name: "",
    job: ""
  });
const handleChange = (e) => {
    //alert(`So your name is `);
    const value = e.target.value;
    setState({
      ...state,
      [e.target.name]: value
    });
  };

  const handleSubmit = (e) => {
  $("#name").val("")
    e.preventDefault();
    const data = {
    name: state.name,
      email: state.job
  };
    
    axios.post('https://xxxxxxxxxxx/',data).then(function(response) {
    console.log(response.data);
});

CodePudding user response:

Just remove it from the state

 const handleSubmit = (e) => {

    setState({
      ...state,
      name: ""
    });
   ....
  }

CodePudding user response:

You have used value={state.name}

So on submit just clear state.name

const handleSubmit = (e) => {
......
setState({...state,name:''});
..........
});
  • Related