Search code examples
reactjsprop-drilling

Prop drilling a function


I want to call the function onChangeStep() which lives in App.js from the third component down

What's the better way of doing this ? Right now I'm trying to drill it all the way down using props and it's still now working.

App.js --> Comp2 --> Comp3 -> onChangeStep

Main Component

  import React, { Component } from "react";

    export default class App extends Component {
      state = {
        var: ""
      };

      onChangeStep() {
        this.setState({ var: "changed" });
      }
      render() {
        return (
          <div>
            <Comp2 onChangeStep={this.onChangeStep.bind(this)} />
          </div>
        );
      }
    }

Comp2

    <Comp3
      onChangeStep={this.props.onChangeStep}
    />

Comp3

import React from "react";

function handleClick(e, props) {
  this.props.onChangeStep();

}

const Comp3 = props => {
  return (
    <div className="column">
      <img
        onClick={e => handleClick(e, "src")}
        alt=""
        src="/cars"
        className="ui image"
      />
    </div>
  );
};

export default Comp3;

Solution

  • Since your Comp3 is a function, the "props" object is only available inside the scope of the const Comp3. A quick fix would be to turn Comp3 into a class component, like this:

    import React, { Component } from "react";
    
    class Comp3 extends Component {
    
      handleClick = (e, props) => {
        this.props.onChangeStep();
      }
    
      render() {
        return (
          <div className="column">
    
          <img
            onClick={e => this.handleClick(e, "src")}
            alt=""
            src=""
            className="ui image"
          />
        </div>
        );
      }
    }
    
    
    export default Comp3;
    

    To avoiding passing props through a long chain of components you should read about React.Context