Last active
April 30, 2019 02:25
-
-
Save AlexHenkel/1f7f7df76bd99a9ff0dab603735cc139 to your computer and use it in GitHub Desktop.
Simple form component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
export default class Form extends Component { | |
// Guardamos directamente en el state nuestros valores del formulario inicializados con string vacío | |
state = { | |
firstName: "", | |
lastName: "", | |
email: "" | |
}; | |
/* | |
* Aplicando curry a la funcion onChange, podemos tener una función que modifique el state | |
* y por lo tanto los valores de nuestros inputs (Los cuales son controlados) | |
*/ | |
onChangeValue = name => event => | |
this.setState({ [name]: event.target.value }); | |
// En el evento normal de onSubmit, tenemos acceso directo al state y a nuestros valores | |
onSubmit = event => { | |
event.preventDefault(); | |
const { firstName, lastName, email } = this.state; | |
console.log({ firstName, lastName, email }); | |
// Aquí hacemos uso de los valores del formulario. Podría insertar una validación en este punto | |
}; | |
render() { | |
const { firstName, lastName, email } = this.state; | |
return ( | |
<form onSubmit={this.onSubmit}> | |
<input | |
type="text" | |
// Al poner explicitamente el valor del input, se vuelve controlado | |
value={firstName} | |
// Los inputs controlados necesitan explicitamente una función de onChange para modificar el valor | |
onChange={this.onChangeValue("firstName")} | |
/> | |
<input | |
type="text" | |
value={lastName} | |
// La función tiene un parametro adicional, la cual es el id para identificar nuestro valor y que se modifique correcto | |
onChange={this.onChangeValue("lastName")} | |
/> | |
<input | |
type="email" | |
value={email} | |
onChange={this.onChangeValue("email")} | |
/> | |
<button type="submit">Envíar</button> | |
</form> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment