Search code examples
javascriptreactjsformsjsxmdbreact

How to get names and the values from dynamic form. (REACTJS)


I am renderin this form dynaimcatlly in the render, How to get names and values when submit was cicked?

This is the parte os the code here form are generated from an array.

import React, { Component, Fragment } from 'react';
import { MDBContainer, MDBBtn, MDBModal, MDBModalBody, MDBModalHeader, MDBModalFooter, MDBIcon} from 'mdbreact';
import { Form, Input, DatePicker, Button } from "antd";
import { connect } from "react-redux";
import axios from "axios";
import moment from "moment";
//import { createHashHistory } from 'history';
import TimeStamp from "./TimeStamp"; //DEBUG.

const FormItem = Form.Item;



class ModalPage extends Component {

constructor(props) {


    super(props);
};




state = {
    modal: false
};



toggle = () => {
    this.setState({
    modal: !this.state.modal
    });
}

handleFormSubmit = async (event, requestType, itemID) => {
    event.preventDefault();
    console.log("@@@@@@@@-----event---->", event)
    console.log("@@@@@@@@-----requestType---->", requestType)
    console.log("@@@@@@@@-----itemID---->", itemID)


    // Se define en Orígen en DynForm.
    const postObj = {
    fecha_alta: event.target.elements.fecha_alta.value,
    nombre: event.target.elements.nombre.value,
    usuario_id: event.target.elements.usuario_id.value
    }

    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.headers = {
    "Content-Type": "application/json",
    Authorization: `Token ${this.props.token}`,

    };

    // Transpaso de variables recibidas:
    let ApiPath =  this.props.data[0].ApiEndPointPath;





    if (requestType === "post") {
    await axios.post(`http://192.168.196.49:8000/${ApiPath}/api/create/`, postObj)
        .then(res => {
        if (res.status === 201) {
            this.setState({modal: false});
            //this.props.history.push(`/proyectos/clientes/`);
            window.location.reload(true);


        }
        })
    } else if (requestType === "put") {
    await axios.put(`http://192.168.196.49:8000/${ApiPath}/api/${itemID}/update/`, postObj)
        .then(res => {
        if (res.status === 200) {
            this.setState({modal: false});
            //this.props.history.push(`/proyectos/clientes/`);
            window.location.reload(false);
        }
        })
    }
};

deleteDato(recibe){
    //<ModalBorrar />
    //event.preventDefault();
    //const articleID = this.props.match.params.articleID;
    console.log("##_deleteDato## el valor es: ", recibe );
    axios.defaults.headers = {
    "Content-Type": "application/json",
    Authorization: `Token ${this.props.token}`
    };
    let ApiPath =  this.props.data[0].ApiEndPointPath;

    axios.delete(`http://192.168.196.49:8000/${ApiPath}/api/${recibe}/delete/`)
    .then(res => {
    if (res.status === 204) {
        console.log("Dato Borrado!!!");
        this.setState({modal: false});
        window.location.reload(false);


    }
    })
};





//DEBUG:
render() {

    let DynForm = this.props.DynForm;




    const debug = {
    Mensage: "Campo personalizado para una nota específica.",
    Fichero: "Modal.js",

    };


    TimeStamp(debug, this.props);






    const renderHerramientaButton = ()=>{
    if( this.props.TipoBoton === "editar"){ //------------ --Editar --------------

        return <MDBIcon className="light-blue-text" icon="edit" size="1x" onClick={this.toggle}/>
    } else if( this.props.TipoBoton === "nuevo"){ //---------Nuevo --------------

        return <MDBBtn size="sm" color="light-blue" onClick={this.toggle}>Nuevo</MDBBtn>

    } else if( this.props.TipoBoton === "borrar"){ //------- Borar --------------

        return <MDBIcon className="red-text" icon="trash-alt" size="1x" onClick={this.toggle}/>

    } else { 

        return <MDBIcon className="red-text" icon="flushed" size="1x" onClick={this.toggle} />
    }
    }





    const NuevosDatos = ()=>{
        return (
        <MDBContainer>
        {/* BUTTON que se renderisa en la página anterior.*/} 
        {renderHerramientaButton()} 

        {/* MODAL */}
        <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
        <MDBModalHeader  toggle={this.toggle}>
            <p className="text-uppercase">{this.props.data[0].ModalTitleNuevo}</p>
        </MDBModalHeader>
        <MDBModalBody>

            <Form
            onSubmit={event =>
            this.handleFormSubmit(
                event,
                this.props.requestType,
                this.props.itemID
            )
            }
            >

            {/* Usando Tenary operation */}
            <div>
            {DynForm.map((value) => (
                <Fragment>
                <FormItem label={value.label}>

                {value.tipo === "input" ? 
                <Input name={value.nombre} placeholder={value.placeholder} defaultValue={value.defaultValue}/> : 
                <DatePicker name={value.nombre} defaultValue={moment(value.defaultValue)}/>}




                </FormItem>

                </Fragment> 

            ))}
            </div>



            <FormItem>
            <Button type="primary" htmlType="submit" color="#389e0d">
                {this.props.btnText}
            </Button>
            </FormItem>
            </Form>
        </MDBModalBody>
        </MDBModal>
        </MDBContainer>
        );
    };


    const EditarDatos = ()=>{
    return (
    <MDBContainer>
    {/* BUTTON que se renderisa en la página anterior.*/} 
    {renderHerramientaButton()} 

    {/* MODAL */}
    <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
    <MDBModalHeader toggle={this.toggle}>
        {this.props.data[0].ModalTitleEditar}
    </MDBModalHeader>
    <MDBModalBody>

        <Form
        onSubmit={event =>
            this.handleFormSubmit(
            event,
            this.props.requestType,
            this.props.itemID
        )
        }
        >

        {/* Usando Tenary operation */}
        <div>
            {DynForm.map((value) => (
                <Fragment>
                <FormItem label={value.label}>

                {value.tipo === "input" ? 
                <Input name={value.nombre} placeholder={value.placeholder} defaultValue={value.defaultValue}/> : 
                <DatePicker name={value.nombre} defaultValue={moment(value.defaultValue)}/>}

                </FormItem>

                </Fragment> 

            ))}
            </div>

        <FormItem>
        <Button type="primary" htmlType="submit" color="#389e0d">
            {this.props.btnText}
        </Button>
        </FormItem>
        </Form>
    </MDBModalBody>
    </MDBModal>
    </MDBContainer>
    );
};



    const BorradoDatos = ()=>{
    return (
    <MDBContainer>
    {/* BUTTON que se renderisa en la página anterior.*/} 
    {renderHerramientaButton()} 

    {/* MODAL */}
    <MDBModal isOpen={this.state.modal} toggle={this.toggle}  backdrop={false}   >
    <MDBModalHeader toggle={this.toggle}>
        {this.props.data[0].ModalTitleBorrar}
    </MDBModalHeader>
    <MDBModalBody>

    <p className="text-md-left">{this.props.campos[0].label}{": "}{this.props.formdataNombre}
        <br></br>
        {this.props.campos[2].label}{": "}{this.props.formdata_Usuario_id}
        <br></br>
        {this.props.campos[1].label}{": "}{this.props.formdataFecha_alta}
        </p>


    </MDBModalBody>
    <MDBModalFooter>                            
        <MDBBtn outline color="danger" size="sm" onClick={() => this.deleteDato(this.props.itemID)}>{this.props.btnText}</MDBBtn>
        <MDBBtn outline color="success" size="sm" onClick={this.toggle}>{this.props.btnText2}</MDBBtn>
        </MDBModalFooter>
    </MDBModal>
    </MDBContainer>
    );
};





    if ( this.props.TipoBoton === "editar") {

    return  (
        <EditarDatos />

        );
    } else if ( this.props.TipoBoton === "borrar") {

    return  (
        <BorradoDatos />

        );
    } else {
    return  (
        <NuevosDatos />

        );

    }









}
}

const mapStateToProps = state => {
    return {
    token: state.token
    };
};

export default connect(mapStateToProps)(ModalPage);
  • the name is know because is comming from the array, the importante thing is the value introduced by the user.

The form used is from mdbreact. Forms are generated correctly. I only need to get data value introduced in each from to prepare my postobject. So it can be saved to the database.

Thank you.


Solution

  • What you're describing is regular HTML where each input element maintains its value in its DOM node. But that's not the way it works with React. With React you have to manage the state of all the input elements yourself by adding the onChange property to each input element. So when the user click the submit button, you already have all the values in the state of your component.

    For example:

    // Create the value state
    state = { value: "" };
    
    // Handle the input change
    onChange = (event) => {
      this.setState(value: event.target.value);
    }
    
    // Render the Input element
    <Input name='test' value={this.state.value} onChange={this.onChange} />