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

Time:01-16

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

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>
  );
};

CodePudding user response:

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

CodePudding user response:

You need to pass the score value from the Card component to the Score component as a prop.

In the Card component, you can pass the score value as a prop to the Score component when you render it:

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

Then in the Score component, you can access the score prop using props.score and use it to render the score:

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

CodePudding user response:

You shall use props.

Using props, you can pass data from one component to the other. In your case, you can pass the score value from your card component to the score component.

In your card component, you will pass the score value as a prop:

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

Now in your Score component, you will render the score value using props.score:

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

CodePudding user response:

Another way if you want to pass props from parent to many children with complex structure. You can use "React Context" and also still have some other library for manage react state eg. Redux, Recoil, ...

CodePudding user response:

Import the score component in your card component and pass the prop from parent in your child component,Reactjs has a concept of props drilling

// Card.js
return (
    <div>
         //pass the prop from here
        <Score score={score} />
    </div>
);

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