0

In React JS, I am trying to create a function that updates the state on the onChange event of an input field, with the value of the input.

The state model has to stay like this, because I have to post it like this (to match API structure etc).

But I don't know how to get to the 'answers' part of the state for each record.

// State --------------------------------------
state = {
    values: [
      //1
      {
        section: "a",
        answers:
        {
            1a: 1,
            1b: 2,
            1c: 3,
            1d: 4,
            1e: 5
        }   
      },
      //2
      {
        section: "b",
        answers:
        {
            2a: 1,
            2b: 2,
            2c: 3,
            2d: 4,
            2e: 5,
            2f: 6,
            2g: 7,
            2h: 7
        }   
      }
   ]
}

// Set value ----------------------------------
  setValue = (key, val) => {
    this.setState((state) => ({ 
      values: {
        ...state.values,
        [key]: val
      }
    }));
  };

// Handle input change ------------------------
  handleChange = key => e => {
    this.setValue(key, e.target.value)
  };

//Usage ---------------------------------------
<input
   id="input1"
   type="number" 
   onChange={handleChange(values.1a)}
   defaultValue={values.1a}
/>
<input
   id="input2"
   type="number" 
   onChange={handleChange(values.2c)}
   defaultValue={values.2c}
/>
1
  • At the moment, it just creates a new state key and value, but need to update the existing state! Commented Apr 6, 2020 at 13:07

1 Answer 1

1

You could try codes below :

// Example class component
class Thingy extends React.Component {
   constructor(props) {
   super(props)
   this.state = {
       values: [
      //1
      {
        section: "a",
        answers:
        {
            a1:1,
            b1:2,
            c1:3,
            d1:4,
            e1:5
        }   
      },
      //2
      {
        section: "b",
        answers:
        {
            a2:1,
            b2:2,
            c2:3,
            d2:4,
            e2:5,
            f2:6,
            g2:7,
            h2:7
        }   
      }
   ]
    }
  }
   
  
  setValue = (Key, val) => {
    
    let output = this.state.values.map(value=>{
       if (Key in value.answers) 
       {
          let tempValue = {
              ...value,
              answers:
              {
                 ...value.answers,
                 [Key] : Number(val)
              }
          }
          return tempValue
       }
       else
       {
          return value
       }
    })
    
    this.setState({
       values:output
    })
  }; 
  
  handleChange =(e, key) => {
    this.setValue(key, e.target.value)
  }
  
  getDefaultValue=(Key)=>{
    let output
    this.state.values.forEach(value=>{
       if (Key in value.answers) 
       {
          output = value.answers[Key]
       }
    })
    return output
  }
  
  render() {
   
    return (
      <div>   
         <input id="input1" type="number" onChange={(e)=>this.handleChange(e,"a1")} value={this.getDefaultValue("a1")} />
         <input id="input2" type="number" onChange={(e)=>this.handleChange(e,"c2")} value={this.getDefaultValue("c2")} /> 
      </div>
    )
  }
}

// Render it
ReactDOM.render(
  <Thingy title="I'm the thingy" />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.