Select Page

Hey devs, here is a new article on reactJS. Today we are going to add an alert in reactJS. Let’s start by installing the react-bootstrap library, then we import it in our project.

npm I react-bootstrap

import Alert from 'react-bootstrap/Alert'

Now we can start code it inside the return of a function. We want the alert to appear just after the user presses a button. So, before we actually code the alert we need to add something in the state. For this example I will use “useState”. If you don’t know how to use it, check my article about it!

const [PopUp, setPopUp] = useState(false)

After we add this, we can code the alert.

<Alert show={PopUp} variant="info" onClose={() => setPopUp(false)}   
  dismissible>
    <Alert.Heading>OPS!</Alert.Heading>
    <div>Email or password wrong</div>
</Alert>

In the above code, you can see the content of our function. “show” accepts booleans, if the boolean is true, the alert will show. That’s where I used the value I created before. When the user will click on a button, its value will be true and the alert will show. The “variant” indicates what kind of alert we are showing the user. There are different types of them:

  • primary
  • secondary
  • success
  • danger
  • warning
  • info
  • light
  • dark

I also added the possibility to close the alarm for the user. The alarm is now “dismissible”. When the user closes the alarm, the value of PopUp will change from “false” to “true” and the alarm will close.

This is the end of this short article on how to add an alert in reactJS. Let me know what you think of it!

Check bootstrap website

Check for other posts