How to send a form to my REST APi in React?

0

Good afternoon, I have this form in my render

  <form className="form-horizontal" role="form">

                   <p><input type="text" className="form-control" 
                    id="name" placeholder="Name" required/></p>
                    <input type="submit" value="send" />

    </form>

And in my api I have a url per post that would be localhost:3000/api/categories/create/:nombre in name would go the name entered in the form. What is the best way to do this in React?

    
asked by Santiago D'Antuoni 13.01.2017 в 19:42
source

1 answer

4

I see that you have doubts about "good practices" in React. All of them can be cleared if:

Preferably pay more attention to articles of personalities that handle the subject well.

Making a submit in React is the same as in VanillaJS, there is no greater mystery. Although in React the events are not native, at the level of functionality there are no major differences.

<form onSubmit={this.onSubmit.bind(this)}>
  <input type="text" value={this.state.name} onChange={this.onInputChange.bind(this)} />
  <button type="submit">Enviar nombre</button>
</form>

...
onInputChange (e) {
  this.setState({ name: e.target.value });
}

onSubmit (e) {
  fetch ('localhost:3000/api/categories/create/${this.state.name}', {
    method: 'POST'
  })
  .then(res => res.json())
  .then(res => {
    if (res.success) { // exito
      alert('Categoría creada');
    }
  });
}

When dealing with forms, we tend to talk about controlled and uncontrolled components. An uncontrolled component is a self-controlled element without being dependent on or being synchronized with a context. You can think of a <input type="text" value="Hola"/> as an uncontrolled component.

On the other hand, a controlled component is one that is controlled by a context, always being synchronized with it, for example: <input type="text" value={this.state.name} onChange={this.onInputChange.bind(this)} /> . In this link you can see a post that talks about this.

Making a controlled component has many advantages compared to an uncontrolled one; ergo, it is not a "must be", but a "could be". Some advantages for forms are:

  • instant validation
  • status change automatically (for example, in the case of a button)
  • force an input format (and even change it in real time)
answered by 13.01.2017 / 20:36
source