skip to Main Content

I have a form containing two fields of input; name and mark

I want to update a property depending on which field is changing, instead of making two (will be increasing) functions to handle each field individually.

Here is the current code which only updates the name property with the value:

    handleStudentChange(e) {
        console.log(e.target)
        var value = e.target.value
        console.log("value: ", value)
        var field = e.target
        //e.target returns <input id="mark1" class="form-control" type="number" placeholder="Mark 1" value="40">

        this.setState({
            activeStudent: {
                ...this.state.activeStudent,
                name: value
            }
        })
    }

Field can take the value of the target property name such as name or mark1 by tapping into the e.target.id property. Is there a way to cast field as the property to use field:value or any other better way of going about the whole thing? Thanks in advance 🙂

2

Answers


  1. handleChange = (e) => {
       const { name, value } = e.target;
       this.setState({ ...activeStudent, [name]: value });
    };
    

    the important thing to use this approach, you should have input name prop set as the state property. for example, if activeStudent has "name" property, corresponding input should be set

              <input
                    value={this.state.activeStudent.name}
                    onChange={handleChange}
                    type="text"
                    // this is important part
                    name="name"
                    id="name"
                         
              />
    
    Login or Signup to reply.
  2. You can set a attribute for key value.

    <input id="mark1" class="form-control" type="number" placeholder="Mark 1" value="40" key="mark" />
    <input id="name1" class="form-control" placeholder="Name 1" value="Test Name" key="name" /> 
    

    Then you can get that attribute by calling e.target.getAttribute(‘key’).

    handleStudentChange(e) {
        var value = e.target.value
        var key = e.target.getAttribute('key')
    
        this.setState({
            activeStudent: {
                ...this.state.activeStudent,
                [key]: value
            }
        })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search