Search code examples
javascriptreactjsparent-childprop

How do I pass a React prop from Parent to Child, to another Child?


I currently have my Parent set up as follows, which I'm then passing props to

 class WorkoutPlan extends React.Component {
  constructor() {
    super();
    this.state = {
      workoutPlan: {}
    };
  }

  componentDidMount() {
    axios
      .get("/api/workout-plan")
      .then(response => {
        this.setState({ workoutPlan: response.data });
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    const { workoutPlan } = this.state;
    // const workoutPlan = this.state.workoutPlan;

    return (
      <div>
        <h1>{workoutPlan.Name}</h1>
        <button className="button" onClick={this.handleClick}>
          Click Me
        </button>
        <Workout {...workoutPlan.workout} />
      </div>
    );
  }
}

Then in my child, I'm wanting to pass those same props to another Child

import React from "react";
import Exercise from "./Exercise";

const Workout = props => {
  return (
    <div>
      <h2>"Workout for {props.day}"</h2>
      <Exercise {...workoutPlan.workout} />
    </div>
  );
};

export default Workout;

I can't seem to figure out how I would go about doing this. I'm being told that the setup is exactly the same as the 1st child, but when I enter in the same code, it's not working.


Solution

  • You can pass {...props} to your Exercise component so your Workout component should look like this

    import React from "react";
    import Exercise from "./Exercise";
    
    const Workout = props => {
      return (
        <div>
          <h2>"Workout for {props.day}"</h2>
          <Exercise {...props} />
        </div>
      );
    };
    
    export default Workout;