[SOLVED]-CLEAR ALL FIELDS AFTER SUBMIT REACT JS-REACTJS

CLEAR ALL FIELDS AFTER SUBMIT REACT JS-REACTJS

You can bind every input value to a state and empty them when you submit it. here i add an example for the username. you can multiply it and use it.

  const [username, setusername] = usestate('name');
  const submitfunctionwhichdeletes = () => {
       console.log(username);
       setusername('');
  }
  <input ... value={username} onchange={e => setusername(e.target.value)} ... />
const compform = ()=>{
 const [formdata,addformdata] = usestate({
  username:"",
  subject:"",
  email:"",
  message:""
 })

 cosnt formsubmit =()=>{
  // make api call
  addformdata({
   username:"",
   subject:"",
   email:"",
   message:""
  })
 }   
 
 const formdata = (e,filed)=>{
  const temp = {...formdata}
  if (filed === "username"){
     temp.username = e.target.value
  }
  else if(filed === "subject"){
    temp.subject = e.target.value
  }
  else if(filed === "email"){
    temp.email = e.target.value
  }
  else if(filed === "message"){
    temp.message = e.target.value
  }
  addformdata(temp)
 }
 
 return(
    <>
     <input type='text' placeholder='name' name='username' 
      value={formdata.username} onchange={(e)=>formdata(e,username)}/>
     <input type='text' placeholder='subject' name='user_subject' 
      value={formdata.subject}  onchange={(e)=>formdata(e,subject)}/>
     <input type='text' placeholder='your email here... ' name='user_email' 
     value={formdata.email} onchange={(e)=>formdata(e,email)}/>
     <textarea rows={5} placeholder='message' name='message' 
      value={formdata.message} onchange={(e)=>formdata(e,message)}/> 
     <button onclick = {(e)=>formsubmit()}>submit</button>
    <>
 )
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments