Reputation: 1929
It's a pain to work with react.js when it comes to form. I was from angular, because of 2 ways binding things are great, it's fast to integrate stuff. But when in react I admit I'm lost.
Says it's a user profile, I got this data from API
var profile = {
name:"Gaila",
age:22,
skills: [{id:1,name:"react"},{id:1,name:"angular"}],
club: [{id:1,name:"dancing"},{id:1,name:"hiking"}],
description: "some long string"
};
on the UI I have text input
, textarea
, checkbox
and select
.
How would I handle it when user clicked to save? Do I have to bind every single input elements with onChange? like handleNameChange, handleAgeChange, handleSkillsChange.. omg it's ridiculous.
So ref came into my mind, easy, just do ref="name"
and I can get it by ReactDOM.findDOMNode(this.refs.name).value
, but wait, it doesn't work on <select>
, it's bad sometime I use ref, sometime I go with handle function.
Guys, I seriously, really need help!
Upvotes: 1
Views: 925
Reputation: 3062
Here is an example of reusing an event handler and picking up the differences from the event. See it in action at codepen.
const FormFunc = () => {
const changeHandler = (e) => {
console.log(`e.target.name, name: `, e.target.name, e.target.value)
}
return (
<form>
<input onChange={changeHandler} type='text' name='firstName' />
<input onChange={changeHandler} type='text' name='surname' />
<input onChange={changeHandler} type='phone' name='phone' />
<input onChange={changeHandler} type='email' name='email' />
</form>
)
}
Upvotes: 1
Reputation: 81
If you only need to extract form values, you can use form-serialize - it's available as a package through npm.
In your component, add a submit event to your form:
<form onSubmit={this.handleSubmit}>
Your handler extracts the form like so:
handleSubmit = (event) => {
event.preventDefault()
const values = serializeForm(event.target, { hash: true })
console.log(values)
}
Upvotes: 0