Search code examples
reactjsmdbreact

How to get reactJS to render a state variable


I am just starting to examine react forms. I'm running into a issue where react is flagging the line in my render where I try to populate the input box label. Here is the code of my app:

import React, { Component } from 'react';
import './App.css';
import { Container, Row, Col, Input, Button, Fa, Card, CardBody } from 'mdbreact';


class App extends Component {

  constructor(props) {
    super(props);
    this.state = { 
      name: {
        valid: true,
        value: '',
        label: 'Your Name',
        length: 0
      }
    }

    this.saveData = this.saveData.bind(this);
  } 

  saveData() {

    let currentComponent = this;

    var validData = true;
    var locaName = {
      valid: true,
      value: '',
      label: 'Your Name',
      length: 0
    }

    locaName.value = document.getElementById("lblName").value;
    locaName.length = locaName.value.length;

    if (locaName.length < 1) {
      validData = false;
      locaName.valid = false;
      locaName.label = "You need to enter your name";
    }

    if (validData == false) {
      currentComponent.setState({ name:locaName });
    }

  }

  render() {

    return (
      <div className="App">
        <div className="d-flex flex-wrap justify-content-center position-absolute w-100 h-50 align-items-center align-content-center">
          <Container>
            <Row>
              <Col md="6">
                <Card>
                  <CardBody>
                    <form>
                      <p className="h4 text-center py-4">Sign up</p>
                      <div className="grey-text">
                        <Input id="lblName" label={this.name.label} icon="user" group type="text" />
                        <Input id="lblEmail" label="Your email" icon="envelope" group type="email" />
                        <Input id="lblConfirmEmail" label="Confirm your email" icon="exclamation-triangle" group type="text" />
                      </div>
                      <div className="text-center py-4 mt-3">
                        <Button color="cyan" onClick={() => 
                        { 
                        this.saveData();
                        }}>Save</Button>
                      </div>
                    </form>
                  </CardBody>
                </Card>
              </Col>
            </Row>
          </Container>
        </div>
      </div>
    )
  }
}

export default App;

at this point, all i am trying to do is render the form with the label of the name input box being 'Your Name' and if no name is entered, to have react re-render the form with the label of the name input box being 'You need to enter your name'.

Any assistance is greatly appreciated.


Solution

  • In order to reference state variables you need to use this.state.name, i'm only seeing this.name in your render function