Need a little help with React

Need a little help with React
0

#1

I’m currently in the middle trying to wrap my head around React. My current problem is that while I know how to pass info up the stack, I’m struggling passing it down. Here is what I’m trying to do:

 class MyBox extends React.Component {
  constructor (props) 
  {  
    super();
    this.state={ on:props.on, id:props.id, changeFunc:props.change };
  }
  
  handleClick ()
  {   
    this.state.changeFunc(this.state.id);
  }
  render(){
    if(this.state.on)
      {
        return ( <div className="redBox" onClick={ this.handleClick.bind(this) }></div> );
      }
    return ( <div className="blueBox" onClick={ this.handleClick.bind(this) }></div> );
  }
}


class MiddleMan extends React.Component {
  constructor (props){ super(); this.state = { passup:props.change, arr:props.arr }; }
 
  drawGrid(){
    for(var i=0;i<this.props.arr.length;i++)
       {
        arr.push((<MyBox  on={this.state.arr[i]} id={ i } change={ this.state.passup.bind(this) }/>));
       }
    return arr;
  }
  render(){
    return ( <div> { this.drawGrid(5) }</div> );
  }
}

class Layout extends React.Component {
  constructor(props){ 
  super();
    this.state={ arr:props.arr };
  }

updateArr(ind){ 
this.state.arr[ind]=!this.state.arr[ind]; //invert
this.setState({arr:this.state.arr});
}  
  
render(){
  return ( 
    <div>
    <h1>Testing....</h1> 
    <MiddleMan arr={ this.state.arr } change={ this.updateArr.bind(this) } />
    </div>
  );
  }
}

So the problem is that when updateArr is called(when you click on a box) it is changing the array in Layout but its not updating the MiddleMan component or the MyBox component. I need to be able to do this so I can handle “game” logic by only interacting with the array and let React handle the image updating, if that makes since. If anyone can point out what I’m doing wrong I would be really thankfull.


#2

I’m currently learning React myself, so I may be completely wrong, but try this:

remove bind in MiddleMan drawGrid():

arr.push((<MyBox  on={this.state.arr[i]} id={ i } change={ this.state.passup }/>));

and add function parameter in Layout render():

<MiddleMan arr={ this.state.arr } change={ this.updateArr.bind(this, this.state.arr) } />

Also you should look into Redux.


#3

Thanks Jenovs. I tried what you suggested and it didn’t help. So after messing around with it I finally figured out the problem was that the only place I was setting the “on” state is in the constructor. I fixed it by including

in the handleClick function of the box and now its working fine.