0

Im new to ReactJS, I'm trying to update input value to a different one however, for some reason it is not updating as it should be, I've got the code on stackblitz for more explanation if you want to try it out as it is performing a very strange behaviour. Appreciate your assistance.

Stackblitz: https://stackblitz.com/edit/easy-drag-and-drop-fxs217?file=index.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
  myArray: [
    [123, 364],
    [469, 983]
  ]
};

this.handleInputChange = this.handleInputChange.bind(this);

}

handleInputChange(e, index) {
let updatedState = [...this.state.myArray];
 console.log("updatedstate ", updatedState)
 console.log(e.target.value)
 updatedState[index] = [Number(e.target.value), this.state.myArray[index][1]]
 this.setState=({
   myArray: updatedState
 })
}

render() {
 return (
  <div>
    {this.state.myArray.map((item, index) => (
      <input key={index} type="text" value={item[0]} onChange={(e) => this.handleInputChange(e, 
       index)} />
    ))}
  </div>
  );
 }
}

render(<App />, document.getElementById('root'));
7
  • You should update state only with this.setState() method. Commented Sep 20, 2020 at 12:44
  • What you want to do here>>>>>updatedState[index] = [Number(e.target.value), this.state.myArray[index][1]]<<<< Plus you are not setting the sate anywhere... Commented Sep 20, 2020 at 12:45
  • ....you don't set the state anywhere lol. At the end of you handleInputChange function you need to update the state like so: this.setState({ myArray: updatedState});. P.S. the spread operator doesn't do DEEP clones, and currently your function actually mutates the state array. In this case it won't really be an issue, but in some instances can cause buggy behaviour so just keep it in mind Commented Sep 20, 2020 at 12:46
  • Thanx for your Stackblitz link . But can you explain a bit clearly wht you are trying to achieve ? Commented Sep 20, 2020 at 12:58
  • 1
    Remove the = after this.setState. Also make sure it's myArray: updatedState as you have it here. Your stackblitz snippet works if you do that. Commented Sep 20, 2020 at 13:29

1 Answer 1

1

SOLUTION

  1. Pick the part of your array for which to update by index.
  2. Update it with the new value.
  3. Use the same array to update your state.
  handleInputChange(e, index) {
    let arrayPart = this.state.myArray[index];
    arrayPart[0] = Number(e.target.value) || null;
  
    this.setState({
      myArray: this.state.myArray,
    })
  }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.