Home > Net >  How can i change state in React for a single item inside map with onClick button?
How can i change state in React for a single item inside map with onClick button?

Time:10-31

I'm trying to set state for one item whenever i click the button on it. i have a map that runs on a list of products, it returns a card with a button in it. i want to click on the button and then set the variable as it needs to be for the item. for example:


    const [isShown, setIsShown] = useState(false) // the state. obviously, it's going to show the result on every card inside that map.

        let handleClick = (id: number) => {
            getAmountOfTimesPurchased(id) // a function that returns a number
        }

        return (
    <div> 
    {products.map((product: IProduct) => {
                            return <Card key={product.id}>
                                <Card.Body>
                                    <Card.Text>
                                        <Card.Title>
                                            {product.name}
                                        </Card.Title>
                                        ${product.price}
                                        <br />
                                        {product.amount}
                                    </Card.Text>
                                </Card.Body>
                                <Card.Footer>
                                    <Button onClick={() => {
                                        handleClick(product.id)
                             }}>Purchased For:</Button>{isShown && timesPurchased}
                                </Card.Footer>
                            </Card>
                        })}
                        </div>

    )

so, how can I show the result only for the card that I'm clicking on?

thank you so much for your help in advance!

CodePudding user response:

Instead of a single isShown state that is a boolean value that all rendered cards are using, store the id of the card that is clicked on and is associated with the fetched data.

Example:

const [isShownId, setIsShownId] = useState(null);

const handleClick = (id: number) => {
  getAmountOfTimesPurchased(id);
  setIsShownId(id);
};

return (
  <div> 
    {products.map((product: IProduct) => {
      return (
        <Card key={product.id}>
          ...
          <Card.Footer>
            <Button
              onClick={() => {
                handleClick(product.id);
              }}
            >
              Purchased For:
            </Button>
            {isShownId === product.id && timesPurchased}
          </Card.Footer>
        </Card>
      );
    })}
  </div>
);
  • Related