Reputation: 355
I entered some data in textbox and after that I clicked on the Button. After clicked on the button The data should be reset.
class Header extends Component {
constructor(props) {
super(props)
this.state = {
title: 'React App',
keywords: 'Type Above'
}
}
inputData = (event) => {
console.log(event.target.value)
this.setState({ keywords: event.target.value ? event.target.value : 'Type Above' })
}
handleSubmit = (event) => {
event.preventDefault();
alert('Button Clicked');
this.setState({ keywords: "" });
}
render() {
return (
<div>
<h2>{this.state.title}</h2>
<form onSubmit ={this.handleSubmit}>
<center>
<input type="text"
placeholder="Search Value..."
onChange ={this.inputData} />
<h3>{this.state.keywords}</h3>
</center>
<button> BUtton </button>
</form>
</div>
)
}
}
Data should get reset after button is clicked...
Upvotes: 0
Views: 76
Reputation: 101
You are missing value
attribute for your input
. You need to add something like this value={this.state.keywords}
Upvotes: 0
Reputation: 2922
your problem is that you didn't assign the keywords
value to the input, because the value is correctly deleted after you click the button, you can see it here:
class Header extends Component {
state = {
title : 'React App',
keywords : 'Type Above'
};
inputData = event => {
console.log(event.target.value)
this.setState({ keywords: event.target.value ? event.target.value : 'Type Above' });
};
handleSubmit = event => {
event.preventDefault();
alert('Button Clicked');
this.setState({ keywords: "" });
};
render() {
const { keywords, title } = this.state;
return (
<div>
<h2>{title}</h2>
<form onSubmit={this.handleSubmit}>
<center>
<input
type="text"
placeholder="Search Value..."
onChange={this.inputData}
value={keywords}
/>
<h3>{keywords}</h3>
</center>
<button>Button </button>
</form>
</div>
)
}
}
Hope this helps, Regards.
Upvotes: 0
Reputation: 430
class Header extends Component {
constructor(props) {
super(props);
this.state = {
title: "React App",
keywords: "Type Above"
};
}
inputData = event => {
console.log(event.target.value);
this.setState({
keywords: event.target.value ? event.target.value : "Type Above"
});
};
handleSubmit = event => {
event.preventDefault();
alert("Button Clicked");
this.setState({ keywords: "" });
};
render() {
return (
<div>
<h2>{this.state.title}</h2>
<form onSubmit={this.handleSubmit}>
<center>
<input
type="text"
placeholder="Search Value..."
value={this.state.keywords === 'Type Above' ? '' : this.state.keywords}
onChange={this.inputData}
/>
<h3>{this.state.keywords}</h3>
</center>
<button> BUtton </button>
</form>
</div>
);
}
}
Upvotes: 0
Reputation: 20755
You need to provide value
prop to your input
,
<input type="text"
placeholder="Search Value..."
onChange ={this.inputData}
value = {this.state.keywords}
/>
Lear more about Controlled Component.
Upvotes: 1