Reputation: 958
Not sure what I'm doing wrong here- this should be really simple, but I can't find the info I'm looking for.
I have a form component and I'm trying to be able to render another component, which is passed props from the form ONLY upon submit. As of right now, the component re-renders on handleChange but does not wait for handleSubmit.
class UserInfo extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<h4>{this.props.name}</h4>
</div>
)
}
}
class SearchForm extends React.Component {
constructor(props) {
super(props)
this.state = {name: ''}
this.handleChange= this.handleChange.bind(this);
this.handleSubmit= this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ name: event.target.value })
}
handleSubmit(event) {
event.preventDefault();
this.setState({ name: this.state.name})
alert(this.state.name + ' was submitted');
}
renderUserInfo() {
return <UserInfo name={this.state.name} />
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Username:
<input type="text" name={this.state.name} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
{this.renderUserInfo()}
</div>
)
}
}
Worth noting, this is a simplified version of my problem and I will need "UserInfo" component to be a container eventually, hence the reason for making it a smart component.
Upvotes: 3
Views: 6178
Reputation: 646
Since you're updating the name
onChange, the react re-renders the entire component. You can use a submitted
flag to check whether the info is submitted or not.
class SearchForm extends React.Component {
constructor(props) {
super(props)
this.state = {
name: '',
submitted: false }
this.handleChange= this.handleChange.bind(this);
this.handleSubmit= this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ name: event.target.value })
}
handleSubmit(event) {
event.preventDefault();
this.setState({ submitted: true })
alert(this.state.name + ' was submitted');
}
renderUserInfo() {
return <UserInfo name={this.state.name} />
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Username:
<input type="text" name={this.state.name} onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
{this.state.submitted && this.renderUserInfo()}
</div>
)
}
}
Upvotes: 3