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)