Nat
Nat

Reputation: 749

Clearing Input after submit With react hooks

How do I clear the input after button submit? The text I input is still there after I submit.

Many thanks in advance and greatly appreciated. Thanks again

const [value, setValue] = useState("");

 const handleInput = e => {
        setValue(e.target.value);
      };

    const onSubmit = (e) => {
        e.preventDefault();
        setValue("");
      }
    

    {
 dbdata.map(item => {
                    return(
                        <div className="card mb-5" key={item._id} style={{maxWidth:"70%",height:"70%"}} >
                            <img src={item.photo} className="card-img-top" alt="..." style={{maxWidth:"100%",height:"100%"}} />
                            <div className="card-body" >
                                <h6 className="card-text">{item.reviews.length} Reviews
                                <form className="input-group mb-3" onSubmit={onSubmit}>
                                    <input type="text" className="form-control" placeholder="add a post onChange={handleInput}  value={value} />
                                    <div class="input-group-append">
                                        <button type="submit" class="btn btn-primary" onClick={(e) => {
                                          makePost(value, item._id)}} type="button">Post</button>
                                    </div>                    
                                </form>
                            </div>
                        </div>

                    )
                })
}

Upvotes: 0

Views: 119

Answers (1)

VersifiXion
VersifiXion

Reputation: 2292

You can try to add a form tag with a onSubmit function, which inside sets the value as an empty string after preventing the default behavior of submitting a form

Edit: I see you have a makePost function, I think you can move the code of this function inside of my onSubmit one or putting my code inside of your makePost function

const [value, setValue] = useState("");

 const handleInput = e => {
        setValue(e.target.value);
      };

  const onSubmit = (e) => {
    e.preventDefault();
    setValue("");
  }

<div className="input-group mb-3">
<form onSubmit={onSubmit}
   <input type="text" className="form-control" placeholder="add a post" onChange={handleInput} value={value} /></form>
        <div class="input-group-append">
          <button type="submit" class="btn btn-primary" onClick={(e) => {makePost(value, item._id)}} type="button">Post</button>
        </div>                    
</div>

Upvotes: 2

Related Questions