Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I send the value of a variable from one component to another? (React)

I have two components: Card.js and Score.js

I have a setScore in my Card.js component that increases by 1 every time I click a certain image.

Card.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Card = () => {
  const [score, setScore] = useState(0);

  const incrementScore = () => {
    setScore(score + 1);
    if (score >= 8) {
      setScore(0);
    }
    console.log(score);
  };

  return (
    <div>
    </div>
  );
};

I need to gain access to that specific Score value inside my second component but I can’t figure out how.

Score.js

const Score = () => {
  return (
    <div>
      <p>{`Score: ${score}`}</p>
    </div>
  );
};

>Solution :

You can use props :

// Card.js
return (
    <div>
        <Score score={score} />
    </div>
);

// Score.js
const Score = (props) => {
  return (
    <div>
      <p>{`Score: ${props.score}`}</p>
    </div>
  );
};

Here is the doc

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading