Created
August 17, 2020 00:22
-
-
Save JacobAvila/13224de3f167c6cfae033322d1bc435d to your computer and use it in GitHub Desktop.
Formularios en React.JS
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'; | |
import {Row, Col, Form, Input, Label, FormGroup, Button, FormFeedback} from 'reactstrap'; | |
class App extends Component { | |
constructor(props){ | |
super(props); | |
this.state = { | |
nombre: '', | |
correo: '', | |
edad: '', | |
mensajeNombre: '', | |
mensajeCorreo: '', | |
mensajeEdad: '', | |
invalidNombre: false, | |
invalidCorreo: false, | |
invalidEdad: false, | |
} | |
this.onChange = this.onChange.bind(this); | |
this.enviarAlaBD = this.enviarAlaBD.bind(this); | |
} | |
onChange = e =>{ | |
const {name, value} = e.target; | |
this.setState({ | |
[name]: value, | |
}); | |
} | |
enviarAlaBD = e => { | |
e.preventDefault(); | |
let valido = true; | |
if(this.state.nombre === ''){ | |
this.setState({ | |
invalidNombre: true, | |
mensajeNombre: 'El campo nombre es obligatorio, indica tu nombre', | |
}); | |
valido = false; | |
} | |
if(this.state.correo === ''){ | |
this.setState({ | |
invalidCorreo: true, | |
mensajeCorreo: 'Indica tu dirección de correo', | |
}); | |
valido = false; | |
} | |
if(this.state.edad === ''){ | |
this.setState({ | |
invalidEdad: true, | |
mensajeEdad: 'Indica tu edad', | |
}); | |
valido = false; | |
} | |
if(valido){ | |
//Enviarlo a la base de datos o a otro componente | |
console.log("Se envian los datos " + JSON.stringify(this.state)); | |
} | |
} | |
render(){ | |
return ( | |
<div> | |
<Row> | |
<Col xs="3"></Col> | |
<Col xs="6"> | |
<h2>Registro de Participantes</h2> | |
<Form onSubmit={this.enviarAlaBD}> | |
<FormGroup> | |
<Label>Nombre</Label> | |
<Input type="text" name="nombre" value={this.state.nombre} onChange={this.onChange} invalid={this.state.invalidNombre} /> | |
<FormFeedback>{this.state.mensajeNombre}</FormFeedback> | |
</FormGroup> | |
<FormGroup> | |
<Label>Correo</Label> | |
<Input type="email" name="correo" value={this.state.correo} onChange={this.onChange} invalid={this.state.invalidCorreo}/> | |
<FormFeedback>{this.state.mensajeCorreo}</FormFeedback> | |
</FormGroup> | |
<FormGroup> | |
<Label>Edad</Label> | |
<Input type="text" name="edad" className="col-2" value={this.state.edad} onChange={this.onChange} invalid={this.state.invalidEdad} /> | |
<FormFeedback>{this.state.mensajeEdad}</FormFeedback> | |
</FormGroup> | |
<FormGroup> | |
<Button color="success">Guardar</Button> | |
</FormGroup> | |
</Form> | |
</Col> | |
</Row> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment