Search code examples
reactjsreactstrap

How to setState with name dynamically?


I'm trying to validate each input field. Assuming I have 5 input fields, how do I set 'error' state for each input field. For example, this.setState({error['roleShortName'] : true }), This won't work and in input, invalid={this.state.error["roleShortName"]}.

<FormGroup row>
      <Label for="roleshortname" sm={4}>roleshortname</Label>
            <Col sm={8}>
                 <Input invalid={this.state.error}
                      autoComplete='off'
                      onChange={this.handleChange}
                      type="text"
                      value={this.state.roleShortName}
                      name="roleShortName"
                      />
             </Col>
</FormGroup>

<FormGroup row>
     <Label for="rolefullname" sm={4}>rolefullname</Label>
            <Col sm={8}>
                  <Input invalid={this.state.error}
                   autoComplete='off'
                   onChange={this.handleChange}
                   type="text"
                   value={this.state.roleName}
                   name="roleName"
              </Col>
</FormGroup>
<Button onClick={() => this.handleAddConfirm()}
handleAddConfirm() {

        if (!this.state.roleShortName) {
            this.setState({ error: true })
            return
        }
        else if (!this.state.roleName) {
            this.setState({error: true})
            return
        }

Solution

  • this.setState({error['roleShortName']: true}) won't work. If you want the key to be dynamic, here's how it should look like:

    this.setState({[error['roleShortName']]: true})

    Notice the [] surrounding the key name.

    Edit: I think you're looking for a dictionary to hold an error for each input:

    handleAddConfirm() {
            var newErrors = {...this.state.errors}
            if (!this.state.roleShortName) {
                newErrors["roleShortName"] = true
            }
            else if (!this.state.roleName) {
                newErrors["roleName"] = true
            }
            this.setState({ errors: newErrors })
            return
    }
    

    In your constructor, you should have

    this.state = {errors: {}}