'Issue with React Strap Alert box not closing individually

I wanted to close each alert box when click on X close button of each, here all alert boxes closing together while single click, Please help

<Alert
        variant="danger"
        show={show}
        dismissible
        onClose={() => setShow(false)}
      >
        <Alert.Heading>Oh snap! You got an error!</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </Alert>
      <Alert
        variant="info"
        show={show}
        dismissible
        onClose={() => setShow(false)}
      >
        <Alert.Heading>Oh snap! You got an Alert Message!</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </Alert>
      <Alert
        variant="info"
        show={show}
        dismissible
        onClose={() => setShow(false)}
      >
        <Alert.Heading>Oh snap! You got an Alert Message !</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </Alert>

https://codesandbox.io/s/alert-on-load-without-button-forked-gj59lj?file=/src/App.js



Solution 1:[1]

Currently, you are using the same show state for all three alerts, that's why when show change, all three alerts change too

One solution is to create an AlertContainer that wraps Alert and stores its own show state

const AlertContainer = ({ variant, children }) => {
  const [show, setShow] = useState(true);

  return (
    <Alert
      variant={variant}
      show={show}
      dismissible
      onClose={() => setShow(false)}
    >
      {children}
    </Alert>
  );
};

export default function App() {
  return (
    <div>
      <AlertContainer variant="danger">
        <Alert.Heading>Oh snap! You got an error!</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </AlertContainer>
      <AlertContainer variant="info">
        <Alert.Heading>Oh snap! You got an Alert Message!</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </AlertContainer>
      <AlertContainer variant="info">
        <Alert.Heading>Oh snap! You got an Alert Message !</Alert.Heading>
        <p>Duis mollis, est non commodo</p>
      </AlertContainer>
    </div>
  );
}

Edit Alert on load without button (forked)

Solution 2:[2]

You are reusing one state for all Alerts. Create such a state, that can handle every Alert separately. For example give every Alert an id. Then create a state like this:

{ 
    1: true,
    2: true,
    3: true
}

Finally on close:

const handleClose = (alertId) =>
    setShow((prev) => { return { ...prev, [alertId]: false };
});

https://codesandbox.io/s/alert-on-load-without-button-forked-3j4d87

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hgb123
Solution 2 Igor Gonak