0

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.

Jee Mok
  • 6,157
  • 8
  • 47
  • 80
Kentron.dna
  • 183
  • 11

1 Answers1

0

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} />
HermitCrab
  • 3,194
  • 1
  • 11
  • 10
  • Do you have any example ? – Kentron.dna Apr 11 '20 at 21:26
  • I don´t know how. theese errores: Line 158:27: 'useState' is not defined no-undef Line 158:36: 'initialValue' is not defined no-undef Line 200:14: Unexpected use of 'name' no-restricted-globals – Kentron.dna Apr 11 '20 at 21:43
  • It looks like you are using a React class component, so I will update my answer – HermitCrab Apr 11 '20 at 21:51
  • I have updated my answer for a React class component – HermitCrab Apr 11 '20 at 21:57
  • Sorry my low level but I can't get it because I don't know where to put this code. thks. – Kentron.dna Apr 11 '20 at 22:12
  • The code I posted is the generic way of handling forms with React, you cannot just copy my code into yours. You need to learn how to handle forms with React before you can implement it in your code – HermitCrab Apr 12 '20 at 07:02
  • I have documented and tested some examples, thanks for the help. In the end he concluded that it would not be possible because the obtained value data cannot be correctly correlated in a dynamic environment. – Kentron.dna Apr 12 '20 at 08:50