Skip to content

Instantly share code, notes, and snippets.

@JacobAvila
Created August 17, 2020 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JacobAvila/13224de3f167c6cfae033322d1bc435d to your computer and use it in GitHub Desktop.
Save JacobAvila/13224de3f167c6cfae033322d1bc435d to your computer and use it in GitHub Desktop.
Formularios en React.JS
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