1

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!

Tân
  • 1
  • 15
  • 56
  • 102
Giala Jefferson
  • 1,809
  • 8
  • 20
  • 29
  • 1
    I'm not sure I understand the question. Why do you need to bind change functions if all you care about is submit? Are you trying to submit every time a form value changes? – Dave Newton Mar 06 '17 at 15:32
  • https://stackoverflow.com/questions/21029999/react-js-identifying-different-inputs-with-one-onchange-handler – paqash Mar 06 '17 at 15:40
  • If you don't want to bind an event on every form element (You could reuse the same function remember so it's not that ridiculous) you could use Redux form. – spirift Mar 06 '17 at 15:41
  • @spirift can you show me an example? says u have 20 diff input elements – Giala Jefferson Mar 06 '17 at 15:46
  • As @spirift said, You can use redux-form to manage all your forms state inside redux-store. You can start with these [examples](https://redux-form.com/6.5.0/examples) – Hardik Modha Mar 06 '17 at 18:17

2 Answers2

1

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>
  )
}
spirift
  • 2,994
  • 1
  • 13
  • 18
0

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)
}