I am new to react, and I am having trouble trying to make the input field clear automatically after clicking the submit button. I believe that I have made the component a fully controlled one by react, where the input value is solely dependent on the state's input. Hope someone is able to help. Been stuck for a few hours now. Really not sure where I've gone wrong. Thanks!
import React, { Component } from 'react';
import './App.css';
import Axios from 'axios';
import { Link, BrowserRouter, Route} from 'react-router-dom';
import reviews from './Screen/Reviews';
class App extends Component{
constructor() {
super();
this.state = {
movieName: '',
setReview: ''
};
this.onMovieChange = this.onMovieChange.bind(this);
this.onReviewChange = this.onReviewChange.bind(this);
this.submitReview = this.submitReview.bind(this);
}
onMovieChange(e) {
this.setState({
movieName: e.target.value
});
}
onReviewChange(e) {
this.setState({
setReview: e.target.value
});
}
submitReview(e) {
e.preventDefault();
const movieName = this.state.movieName;
const movieReview = this.state.setReview;
Axios.post('http://localhost:3001/api/insert',
{movieName: movieName, movieReview: movieReview}).then(()=>
{
alert('Insert successfully');
}
)
this.setState({
movieName: '',
setReview: ''
})
}
render() {
return (
<BrowserRouter>
<div className="form">
<form >
<ul className="form-container">
<li>
<h2>Movie Review</h2>
</li>
<li>
<label htmlFor="movieName">
Movie Name {" "}
</label>
<input className="movieName" type="movieName" name="movieName" id="movieName" onChange={this.onMovieChange}>
</input>
</li>
<li>
<label htmlFor="review">Review{" "}</label>
<input className="review" type="review" id="review" name="review" onChange={this.onReviewChange}>
</input>
</li>
<li>
<button onClick={this.submitReview} type="submit" className="button-register-registration ">Submit</button>
</li>
<li>
<Link to="/review" className="button-register-for-sign-in" ><h4>Go to reviews</h4></Link>
</li>
</ul>
</form>
<main>
<div className="content">
<Route path={"/review"} component={reviews}></Route>
</div>
</main>
</div>
</BrowserRouter>
);
}
}
you are treating input as an uncontrolled component, so react cannot control its value and hence not sync with its state. So make your input controlled by updating as below
<input className="movieName" type="movieName" name="movieName" id="movieName" onChange={this.onMovieChange} value={this.state.movieName}>