Reputation:
I have some code which catches a submitted form data.
Here it is:
class UserInfo extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
const formData = {};
for (const field in this.refs) {
formData[field] = this.refs[field].value;
}
console.log('-->', formData);
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<input ref="fullname" className="fullname" type='text' name="fullname"/>
<input ref="email" className="email" type='tel' name="email"/>
<input type="submit" value="Submit"/>
</form>
</div>
);
}
}
export default UserInfo;
The above works fine but refs are depreciated so my question is...
How can I change this refs to non-depreciated code?
Upvotes: 0
Views: 36
Reputation: 2006
Just change this :
<input ref="fullname" className="fullname" type='text' name="fullname"/>
<input ref="email" className="email" type='tel' name="email"/>
<input type="submit" value="Submit"/>
to this:
<input ref={fullname => this.fullname =fullname} className="fullname" type='text' name="fullname"/>
<input ref={email => this.email = email} className="email" type='tel' name="email"/>
<input type="submit" value="Submit"/>
now the reference is stored in this.fullname and this.email. don't forget to check if they are null.
I hope it helps.
Upvotes: 1