0

I have the following child component:

    class Adjust extends Component {
        render() {
        const { values, toggleSelector, SELECTOR } = this.props;
        console.log("values are", values"); //this is only being entered once right now
        
        return(
        <div
        key={values}
        style={{
          marginBottom: "25px",
          width: "80vw",
        }}>
         <button
                buttonSelected={values[index]?.add}
                onClick={() => {
                  toggleSelector(index, SELECTOR.ADD);
                }}
          >
         "Add"
        </button>
       </div>
      )}}

And this is how I pass props to this child

<Adjust  values={values} SELECTOR={SELECTOR} toggleSelector={this.toggleSelector}> </Adjust>

I have a console log in my toggleSelector function in my parent component, which shows that it is being entered, but even though the state is changing, the render of Adjust component is not being entered again.

I have tried adding a key to it but that didn't help.

This is the toggleSelector function

      toggleSelector(index, selector) {
        console.log("enter");
        let { values } = this.state;
        values[index][selector] = true;
        if (selector === SELECTOR.ADD) {
          values[index].subtract = false;
        } else if (selector === SELECTOR.SUBTRACT) {
          values[index].add = false;
        } 
        this.setState({
          values,
        });  

}

This was all working fine when Adjust was not a child component but within the parent. Had to make it a child for better code readability

1 Answers1

1

You don't manage values like an immutable variable, values is the same array between renders, you only update it's content.

You can find more information there Correct modification of state arrays in React.js

MoiioM
  • 1,914
  • 1
  • 10
  • 16
  • But the state is updating, because if I do a `console.log(values)` in the parent component, that is updating –  Apr 26 '21 at 17:43
  • 1
    The state is updating but react consider `values` unchanged and does'nt re-render the child. Try with `this.setState({values: [...values]})` and read the linked answer. – MoiioM Apr 26 '21 at 17:45
  • Hello, I'm also facing another issue that the child component is rendering, but the changes are shown by one click delay. So for example, if I click on something it changes after I click on something else. –  Apr 26 '21 at 18:12
  • Could this be also because of the problem in your answer? I'm now updating `values` based on this answer too https://stackoverflow.com/a/45878231/14683403 –  Apr 26 '21 at 18:13
  • The child doesn't render immediatly after click on button ? did you change the parent / child component ? – MoiioM Apr 26 '21 at 20:09