0

I have a react component that contains input boxes. I want to make sure that the input boxes are not empty.

On componentDidMount I run the following function:

this.validateInputLength(this.state.first_name, 'firstNameValid');

as you can see I pass in the value of this.state.first_name and the string 'firstNameValid'.

The problem is that 'firstNameValid' is not setting the state of the component. I was under the impression that I could pass the key of the state object in as a string and it would update, however this does not appear to be working.

See complete code below for more context.

class Test extends Component {

  constructor(props) {
    super(props)

    this.state = {
      first_name: '',
      last_name: '',
      firstNameValid: true,
      lastNameValid: true
    };
  
    this.validateInputLength = this.validateInputLength.bind(this);
  }

  componentDidMount() {

    this.validateInputLength(this.state.first_name, 'firstNameValid');
    this.validateInputLength(this.state.last_name, 'lastNameValid');

  }


  validateInputLength(value, inputType) {

    if (value.length <= 0) {

      this.setState({
        inputType: false
      });

    } else {

      this.setState({
        inputType: true
      });

    }
  }

  render() {
    ........
  }
}
Community
  • 1
  • 1
peter flanagan
  • 9,195
  • 26
  • 73
  • 127
  • You need square brackets around `inputType` like this `this.setState({ [inputType]: true })` – Hardik Modha Apr 18 '17 at 15:58
  • 2
    I was going to add an answer before it was marked as duplicate, but here is a better way to write that function: `validateInputLength(value, inputType) { this.setState({ [inputType]: value.length > 0 }) }` – ndbroadbent Apr 18 '17 at 16:05

1 Answers1

1

You can wrap it in square brackets to achieve what you're after.

var testing = "testable";

var test = {
 [testing]: "value in [testing]"
};

document.getElementById("value").innerText = test.testable;
<p id="value"></p>
Kyle Richardson
  • 5,567
  • 3
  • 17
  • 40