Search code examples
javascriptreactjsreact-dom

Sending state data down to parent component


Many similar posts came up about this topic but none of them makes sense in the context of my application, so I am posting this, let me know if it is a duplicate and that it has an answer already.

A Circle component, renders a simple div element with onMouseMove event handler. Calls the UpdateCoords function which sends the position of the pointer on that element which is stored as a state :

this.state = {
    position: {x: null, y: y}
};

I have a parent component Main which renders the Circle component, now I think I need to use the values of state from the Circle component, but I am not quite sure how.


Solution

  • When you want to pass data from parent to child you use props and when from child to parent use callback function.

    Main Component

    class Main extends React.Component {
      constructor( props ) {
        super(props);
        this.state = {
          position: { x: null, y: null}
        };
      }
      
      updateCoords = (x , y) => {
        this.setState({
          position: {
            x, y
          }
        });
      }
      
      render(){
        return(
            <div className='main-container'>
                <Circle mouseMove={ this.updateCoords }/>
                <pre>
                  <p> x - y:  {this}</p>
                </pre>
            </div>
        );
      }
    }

    Circle Component

    class Circle extends React.Component {
        constructor(props){
          super(props);
          this.state = {
              position: {x: null, y: null}
          }
          
          this.updateCoords = this.updateCoords.bind( this );
        }
        
        updateCoords( evt ){
            let x = evt.clientX;
            let y = evt.clientY;
        
            this.setState({
                position: {
                    x: x,
                    y: y,
                }
            });
            
            this.props.mouseMove(x, y);
        
            console.log("Clicked");
        }
      
        render() {
          return( 
              <div className="circle" onMouseMove={ this.updateCoords }>
                  <span>
                  x: {this.state.position.x}, y: {this.state.position.y}
                  </span>
              </div> 
          );
        }
    }