1

I have a file named Card.js. It contains two states called status and view .

Every time a button is clicked, my status state changes & according to this state my card is hidden.

At the same time, each of my cards has a view state. This increases by 1 according to the click event.

src/components/Card.js


const Card = (props) => {
  const [status, setStatus] = useState(false);
  const [view, setView] = useState(0);

  const handleClick = () => {
    setStatus(!status);
    setView(view + 1);
  };

  return (
    <div>
      <Button onClick={handleClick}>{status ? "Show Component" : "Hide Component"}</Button>
      {status ? null : <div className="card">{props.children} </div>}
    </div>
  );
};
export default Card;

In my app.js file, I return the data in my JSON file with the map method, I print this data to my card component.

src/App.js


const App= () => {
  return (
      <div>
        {post.map((value, index) => {
          return (
            <Card key={index}>
           {// here I want to print the "view" state in my Card.js file.}
            </Card>
          );
        })}
      </div>
  );
};
export default App;

In App.js, I tried to create the view state using the useEffect hook, but every time I click the button, the view state of both my cards is updated at the same time. I don't want it to happen this way.

antzshrek
  • 9,276
  • 5
  • 26
  • 43
Brandt
  • 83
  • 6

1 Answers1

0

You can pass the data in your card as props so that the data is available in your Card module.

{
  post.map((value, index) => {
      return (
        <Card key={index} status={false}>
       {// here I want to print the "view" state in my Card.js file.}
        </Card>
      );
  })
}

And in card module, pass the prop value to useState. I hope this will solve your problem.

const [status, setStatus] = useState(props.status);
T. Nielsen
  • 835
  • 5
  • 18
  • I guess I didn't convey exactly what I wanted to say, we send props to use in "Card.js" the way you said. I want to use the values in Card.js on App.js. – Brandt Aug 01 '22 at 01:15
  • Yes. Thanks for clarification. Now In your case you can lift your state up to App.js if you are not using any state management library. For more Info please read https://reactjs.org/docs/lifting-state-up.html – Sumit kumar Aug 02 '22 at 02:29
  • This is quite complex task but it is the only way if we are not using context hook & state management library like redux. – Sumit kumar Aug 02 '22 at 02:31