0

Tengo este código que muestra un formulario con inputs y al darle al botón de submit envia los datos por POST a un endpoint.

El código funciona correctamente, pero para cada input tengo un evento para recoger el valor y guardarlo en this.state, mi pregunta es si se puede hacer esto de otra forma.

import React, { Component } from "react";
import { Button , Form  } from 'react-bootstrap';

export default class Profile extends Component {

constructor(props) {
    super(props);

    this.state = {
        weight : '',
        height: '',
        imc: '',
    };

    this.handleChangeWeight= this.handleChangeWeight.bind(this);
    this.handleChangeHeight= this.handleChangeHeight.bind(this);
    this.handleChangeImc= this.handleChangeImc.bind(this);

    this.handleSubmit = this.handleSubmit.bind(this);

}


handleChangeWeight(event) {
    this.setState({
        weight: event.target.value,
    })
}

handleChangeHeight(event) {
    this.setState({
        height: event.target.value,
    })
}

handleChangeImc(event) {
    this.setState({
        imc: event.target.value,
    })
}


handleSubmit(event) {
    fetch('http://test-url.local/api/user', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            weight : this.state.weight,
            height : this.state.height,
            imc : this.state.imc,
        })
    });

    event.preventDefault();
}


render() {

    var divStyle = {
        color: 'red',
        margin: '150px 150px 160px 350px',
    };

    return (
        <div style={divStyle}>
            <Form>
                <Form.Group controlId="formBasicSuplementos">
                    <Form.Check id="suplementos" type="checkbox" label="Suplementos" />
                </Form.Group>

                <Form.Group controlId="formBasicWeight">
                    <Form.Label>Peso</Form.Label>
                    <Form.Control id="weight" name="weight" placeholder="weight" onChange={this.handleChangeWeight} />
                </Form.Group>

                <Form.Group controlId="formBasicHeight">
                    <Form.Label>Altura</Form.Label>
                    <Form.Control id="height" name="height" placeholder="height" onChange={this.handleChangeHeight} />
                </Form.Group>


                <Form.Group controlId="formBasicImc">
                    <Form.Label>Imc</Form.Label>
                    <Form.Control id="imc" name="imc" placeholder="imc" onChange={this.handleChangeImc} />
                </Form.Group>

                <Button onClick={this.handleSubmit}>Enviar</Button>
            </Form>
        </div>
    );
}
}

Gracias

1 respuesta 1

0

Copiado/pegado desde las guías de react:

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

Y luego aplicado a tus inputs:

    <Form>
      <Form.Group controlId="formBasicSuplementos">
        <Form.Check id="suplementos" type="checkbox" label="Suplementos" />
      </Form.Group>

      <Form.Group controlId="formBasicWeight">
        <Form.Label>Peso</Form.Label>
        <Form.Control
          id="weight"
          name="weight"
          placeholder="weight"
          onChange={this.handleInputChange}
        />
      </Form.Group>

      <Form.Group controlId="formBasicHeight">
        <Form.Label>Altura</Form.Label>
        <Form.Control
          id="height"
          name="height"
          placeholder="height"
          onChange={this.handleInputChange}
        />
      </Form.Group>

      <Form.Group controlId="formBasicImc">
        <Form.Label>Imc</Form.Label>
        <Form.Control
          id="imc"
          name="imc"
          placeholder="imc"
          onChange={this.handleInputChange}
        />
      </Form.Group>

      <Button onClick={this.handleSubmit}>Enviar</Button>
    </Form>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.