React - How To Compare Props Between Separate Components











up vote
1
down vote

favorite
1












How can I compare if the props between two separate components have the same value?



1- Is what I'm seeking doable?



2- If not, how else could I accomplish the ask below:



The story:




  • I have an array of car objects.
    Each car's name is displayed as <li /> on a <CarList /> component.
    Upon click on each <li/> the car's color is revealed


  • I have a <Question /> component that renders: "What car is (random color here)"?



UI change:
How could I write a method that:




  • Checks if the props.color of <CarList /> === the props.color of <Question />

  • Then it fires a UI change such as:


  • onClick: If the car's color matches the question's color: change the <li /> to green (ie: background-color), else change it to red.


I'm struggling (wondering if it's possible) to compare props from different components + writing a method that checks and executes the UI change above.



This is the code reflecting the explanation above: Also here's the sandbox



// Garage
export default class Garage extends Component {
state = {
cars: [
{ name: "Ferrari", color: "red", id: 1 },
{ name: "Porsche", color: "black", id: 2 },
{ name: "lamborghini", color: "green", id: 3 },
{ name: "McLaren", color: "silver", id: 4 },
{ name: "Tesla", color: "yellow", id: 5 }
]
};

handleShuffle = () => {
this.setState({
cars: [...this.state.cars.sort(() => Math.random() - 0.5)]
});
};

render() {
const { cars } = this.state;
const car = cars.map(car => (
<CarList key={car.id} make={car.name} color={car.color} />
));

const guess = cars
.slice(2, 3)
.map(car => <Question key={car.id} color={car.color} />);
return (
<>
<div>{guess}</div>
<button onClick={this.handleShuffle}>load color</button>
<ul>{car}</ul>
</>
);
}
}

// CarList
class CarList extends Component {
state = {
show: false
};

handleShow = () => {
this.setState({ show: true });
console.log(this.props);
// check for props equality here

//desired result for <li /> would be
// className={ correctColor ? 'green' : 'red'}
};

render() {
console.log("car color props:", this.props.color);
const { make, color } = this.props;
const { show } = this.state;
return (
<li onClick={this.handleShow}>
{make}
<span className={show ? "show" : "hide"}>{color}</span>
</li>
);
}
}

// Question
const Question = ({ color }) =>
console.log("question color prop:", color) || <h1>What car is {color}</h1>;









share|improve this question




























    up vote
    1
    down vote

    favorite
    1












    How can I compare if the props between two separate components have the same value?



    1- Is what I'm seeking doable?



    2- If not, how else could I accomplish the ask below:



    The story:




    • I have an array of car objects.
      Each car's name is displayed as <li /> on a <CarList /> component.
      Upon click on each <li/> the car's color is revealed


    • I have a <Question /> component that renders: "What car is (random color here)"?



    UI change:
    How could I write a method that:




    • Checks if the props.color of <CarList /> === the props.color of <Question />

    • Then it fires a UI change such as:


    • onClick: If the car's color matches the question's color: change the <li /> to green (ie: background-color), else change it to red.


    I'm struggling (wondering if it's possible) to compare props from different components + writing a method that checks and executes the UI change above.



    This is the code reflecting the explanation above: Also here's the sandbox



    // Garage
    export default class Garage extends Component {
    state = {
    cars: [
    { name: "Ferrari", color: "red", id: 1 },
    { name: "Porsche", color: "black", id: 2 },
    { name: "lamborghini", color: "green", id: 3 },
    { name: "McLaren", color: "silver", id: 4 },
    { name: "Tesla", color: "yellow", id: 5 }
    ]
    };

    handleShuffle = () => {
    this.setState({
    cars: [...this.state.cars.sort(() => Math.random() - 0.5)]
    });
    };

    render() {
    const { cars } = this.state;
    const car = cars.map(car => (
    <CarList key={car.id} make={car.name} color={car.color} />
    ));

    const guess = cars
    .slice(2, 3)
    .map(car => <Question key={car.id} color={car.color} />);
    return (
    <>
    <div>{guess}</div>
    <button onClick={this.handleShuffle}>load color</button>
    <ul>{car}</ul>
    </>
    );
    }
    }

    // CarList
    class CarList extends Component {
    state = {
    show: false
    };

    handleShow = () => {
    this.setState({ show: true });
    console.log(this.props);
    // check for props equality here

    //desired result for <li /> would be
    // className={ correctColor ? 'green' : 'red'}
    };

    render() {
    console.log("car color props:", this.props.color);
    const { make, color } = this.props;
    const { show } = this.state;
    return (
    <li onClick={this.handleShow}>
    {make}
    <span className={show ? "show" : "hide"}>{color}</span>
    </li>
    );
    }
    }

    // Question
    const Question = ({ color }) =>
    console.log("question color prop:", color) || <h1>What car is {color}</h1>;









    share|improve this question


























      up vote
      1
      down vote

      favorite
      1









      up vote
      1
      down vote

      favorite
      1






      1





      How can I compare if the props between two separate components have the same value?



      1- Is what I'm seeking doable?



      2- If not, how else could I accomplish the ask below:



      The story:




      • I have an array of car objects.
        Each car's name is displayed as <li /> on a <CarList /> component.
        Upon click on each <li/> the car's color is revealed


      • I have a <Question /> component that renders: "What car is (random color here)"?



      UI change:
      How could I write a method that:




      • Checks if the props.color of <CarList /> === the props.color of <Question />

      • Then it fires a UI change such as:


      • onClick: If the car's color matches the question's color: change the <li /> to green (ie: background-color), else change it to red.


      I'm struggling (wondering if it's possible) to compare props from different components + writing a method that checks and executes the UI change above.



      This is the code reflecting the explanation above: Also here's the sandbox



      // Garage
      export default class Garage extends Component {
      state = {
      cars: [
      { name: "Ferrari", color: "red", id: 1 },
      { name: "Porsche", color: "black", id: 2 },
      { name: "lamborghini", color: "green", id: 3 },
      { name: "McLaren", color: "silver", id: 4 },
      { name: "Tesla", color: "yellow", id: 5 }
      ]
      };

      handleShuffle = () => {
      this.setState({
      cars: [...this.state.cars.sort(() => Math.random() - 0.5)]
      });
      };

      render() {
      const { cars } = this.state;
      const car = cars.map(car => (
      <CarList key={car.id} make={car.name} color={car.color} />
      ));

      const guess = cars
      .slice(2, 3)
      .map(car => <Question key={car.id} color={car.color} />);
      return (
      <>
      <div>{guess}</div>
      <button onClick={this.handleShuffle}>load color</button>
      <ul>{car}</ul>
      </>
      );
      }
      }

      // CarList
      class CarList extends Component {
      state = {
      show: false
      };

      handleShow = () => {
      this.setState({ show: true });
      console.log(this.props);
      // check for props equality here

      //desired result for <li /> would be
      // className={ correctColor ? 'green' : 'red'}
      };

      render() {
      console.log("car color props:", this.props.color);
      const { make, color } = this.props;
      const { show } = this.state;
      return (
      <li onClick={this.handleShow}>
      {make}
      <span className={show ? "show" : "hide"}>{color}</span>
      </li>
      );
      }
      }

      // Question
      const Question = ({ color }) =>
      console.log("question color prop:", color) || <h1>What car is {color}</h1>;









      share|improve this question















      How can I compare if the props between two separate components have the same value?



      1- Is what I'm seeking doable?



      2- If not, how else could I accomplish the ask below:



      The story:




      • I have an array of car objects.
        Each car's name is displayed as <li /> on a <CarList /> component.
        Upon click on each <li/> the car's color is revealed


      • I have a <Question /> component that renders: "What car is (random color here)"?



      UI change:
      How could I write a method that:




      • Checks if the props.color of <CarList /> === the props.color of <Question />

      • Then it fires a UI change such as:


      • onClick: If the car's color matches the question's color: change the <li /> to green (ie: background-color), else change it to red.


      I'm struggling (wondering if it's possible) to compare props from different components + writing a method that checks and executes the UI change above.



      This is the code reflecting the explanation above: Also here's the sandbox



      // Garage
      export default class Garage extends Component {
      state = {
      cars: [
      { name: "Ferrari", color: "red", id: 1 },
      { name: "Porsche", color: "black", id: 2 },
      { name: "lamborghini", color: "green", id: 3 },
      { name: "McLaren", color: "silver", id: 4 },
      { name: "Tesla", color: "yellow", id: 5 }
      ]
      };

      handleShuffle = () => {
      this.setState({
      cars: [...this.state.cars.sort(() => Math.random() - 0.5)]
      });
      };

      render() {
      const { cars } = this.state;
      const car = cars.map(car => (
      <CarList key={car.id} make={car.name} color={car.color} />
      ));

      const guess = cars
      .slice(2, 3)
      .map(car => <Question key={car.id} color={car.color} />);
      return (
      <>
      <div>{guess}</div>
      <button onClick={this.handleShuffle}>load color</button>
      <ul>{car}</ul>
      </>
      );
      }
      }

      // CarList
      class CarList extends Component {
      state = {
      show: false
      };

      handleShow = () => {
      this.setState({ show: true });
      console.log(this.props);
      // check for props equality here

      //desired result for <li /> would be
      // className={ correctColor ? 'green' : 'red'}
      };

      render() {
      console.log("car color props:", this.props.color);
      const { make, color } = this.props;
      const { show } = this.state;
      return (
      <li onClick={this.handleShow}>
      {make}
      <span className={show ? "show" : "hide"}>{color}</span>
      </li>
      );
      }
      }

      // Question
      const Question = ({ color }) =>
      console.log("question color prop:", color) || <h1>What car is {color}</h1>;






      javascript reactjs ecmascript-6 react-props






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 days ago

























      asked 2 days ago









      tonkihonks13

      953719




      953719
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          Yes, you can pass the correct color to the CarList component or the flag whether the CarList is a correct one. Check my sandbox.



          https://codesandbox.io/s/92xnwpyq6p



          Basically we can add isCorrect prop to CarList which has value of correctCar.color === car.color and we use it to determine whether we should render it green or red.






          share|improve this answer





















          • Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
            – tonkihonks13
            2 days ago












          • you can use empty string in that case. I think I also use it in my sandbox. Check it out
            – jamesjaya
            2 days ago






          • 1




            check my getColor() function
            – jamesjaya
            2 days ago






          • 1




            Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
            – jamesjaya
            2 days ago






          • 1




            oh I forgot to hit save, you should be able to see it now
            – jamesjaya
            2 days ago


















          up vote
          2
          down vote













          Theres many ways to do this but the simplest is to send the color in the question down to the car component.



          https://codesandbox.io/s/my4wmn427x






          share|improve this answer





















          • Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
            – tonkihonks13
            2 days ago






          • 1




            <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
            – Shawn Andrews
            yesterday











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402331%2freact-how-to-compare-props-between-separate-components%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          Yes, you can pass the correct color to the CarList component or the flag whether the CarList is a correct one. Check my sandbox.



          https://codesandbox.io/s/92xnwpyq6p



          Basically we can add isCorrect prop to CarList which has value of correctCar.color === car.color and we use it to determine whether we should render it green or red.






          share|improve this answer





















          • Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
            – tonkihonks13
            2 days ago












          • you can use empty string in that case. I think I also use it in my sandbox. Check it out
            – jamesjaya
            2 days ago






          • 1




            check my getColor() function
            – jamesjaya
            2 days ago






          • 1




            Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
            – jamesjaya
            2 days ago






          • 1




            oh I forgot to hit save, you should be able to see it now
            – jamesjaya
            2 days ago















          up vote
          2
          down vote



          accepted










          Yes, you can pass the correct color to the CarList component or the flag whether the CarList is a correct one. Check my sandbox.



          https://codesandbox.io/s/92xnwpyq6p



          Basically we can add isCorrect prop to CarList which has value of correctCar.color === car.color and we use it to determine whether we should render it green or red.






          share|improve this answer





















          • Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
            – tonkihonks13
            2 days ago












          • you can use empty string in that case. I think I also use it in my sandbox. Check it out
            – jamesjaya
            2 days ago






          • 1




            check my getColor() function
            – jamesjaya
            2 days ago






          • 1




            Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
            – jamesjaya
            2 days ago






          • 1




            oh I forgot to hit save, you should be able to see it now
            – jamesjaya
            2 days ago













          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          Yes, you can pass the correct color to the CarList component or the flag whether the CarList is a correct one. Check my sandbox.



          https://codesandbox.io/s/92xnwpyq6p



          Basically we can add isCorrect prop to CarList which has value of correctCar.color === car.color and we use it to determine whether we should render it green or red.






          share|improve this answer












          Yes, you can pass the correct color to the CarList component or the flag whether the CarList is a correct one. Check my sandbox.



          https://codesandbox.io/s/92xnwpyq6p



          Basically we can add isCorrect prop to CarList which has value of correctCar.color === car.color and we use it to determine whether we should render it green or red.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 days ago









          jamesjaya

          647412




          647412












          • Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
            – tonkihonks13
            2 days ago












          • you can use empty string in that case. I think I also use it in my sandbox. Check it out
            – jamesjaya
            2 days ago






          • 1




            check my getColor() function
            – jamesjaya
            2 days ago






          • 1




            Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
            – jamesjaya
            2 days ago






          • 1




            oh I forgot to hit save, you should be able to see it now
            – jamesjaya
            2 days ago


















          • Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
            – tonkihonks13
            2 days ago












          • you can use empty string in that case. I think I also use it in my sandbox. Check it out
            – jamesjaya
            2 days ago






          • 1




            check my getColor() function
            – jamesjaya
            2 days ago






          • 1




            Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
            – jamesjaya
            2 days ago






          • 1




            oh I forgot to hit save, you should be able to see it now
            – jamesjaya
            2 days ago
















          Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
          – tonkihonks13
          2 days ago






          Thank you so much for the explanation and code example. Ideally red or green only triggers upon clicking. Prior to it, it should stay in black. Would/Should I massage this logic on className={.....}?
          – tonkihonks13
          2 days ago














          you can use empty string in that case. I think I also use it in my sandbox. Check it out
          – jamesjaya
          2 days ago




          you can use empty string in that case. I think I also use it in my sandbox. Check it out
          – jamesjaya
          2 days ago




          1




          1




          check my getColor() function
          – jamesjaya
          2 days ago




          check my getColor() function
          – jamesjaya
          2 days ago




          1




          1




          Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
          – jamesjaya
          2 days ago




          Garage.js line 62 correctIndex: Math.random() returns a random number between 0 and 1. I multiply it by the length of cars minus 1, means if the length is 5, the random number would be a random number between 0 and 4. Since I want an integer, I call Math.floor.
          – jamesjaya
          2 days ago




          1




          1




          oh I forgot to hit save, you should be able to see it now
          – jamesjaya
          2 days ago




          oh I forgot to hit save, you should be able to see it now
          – jamesjaya
          2 days ago












          up vote
          2
          down vote













          Theres many ways to do this but the simplest is to send the color in the question down to the car component.



          https://codesandbox.io/s/my4wmn427x






          share|improve this answer





















          • Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
            – tonkihonks13
            2 days ago






          • 1




            <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
            – Shawn Andrews
            yesterday















          up vote
          2
          down vote













          Theres many ways to do this but the simplest is to send the color in the question down to the car component.



          https://codesandbox.io/s/my4wmn427x






          share|improve this answer





















          • Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
            – tonkihonks13
            2 days ago






          • 1




            <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
            – Shawn Andrews
            yesterday













          up vote
          2
          down vote










          up vote
          2
          down vote









          Theres many ways to do this but the simplest is to send the color in the question down to the car component.



          https://codesandbox.io/s/my4wmn427x






          share|improve this answer












          Theres many ways to do this but the simplest is to send the color in the question down to the car component.



          https://codesandbox.io/s/my4wmn427x







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 2 days ago









          Shawn Andrews

          434212




          434212












          • Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
            – tonkihonks13
            2 days ago






          • 1




            <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
            – Shawn Andrews
            yesterday


















          • Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
            – tonkihonks13
            2 days ago






          • 1




            <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
            – Shawn Andrews
            yesterday
















          Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
          – tonkihonks13
          2 days ago




          Thank you! So with this approach where/how <Question/> becomes aware of the questionColor sent down to <CarList />?
          – tonkihonks13
          2 days ago




          1




          1




          <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
          – Shawn Andrews
          yesterday




          <Question> is not aware it's color is being sent to <CarList>. In this approach the garage is aware of both colors and chooses to additionally send down the question color to <CarList> so that each car can do a comparison against its own car color :)
          – Shawn Andrews
          yesterday


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402331%2freact-how-to-compare-props-between-separate-components%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Sphinx de Gizeh

          Dijon

          Équipe cycliste