Published on

How to Import Alert / AlertTitle Component in Material UI

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Import Alert / AlertTitle Component in Material UI

Material UI provides an Alert component to display messages with different severity levels. However, depending on the version of Material UI you are using, the way to import Alert and AlertTitle differs.

Importing Alert in Material UI v4

In Material UI v4, Alert and AlertTitle were part of the @material-ui/lab package, which needed to be installed separately:

Install @material-ui/lab

npm install @material-ui/lab
# or
yarn add @material-ui/lab

Import Components

import Alert from '@material-ui/lab/Alert'
import AlertTitle from '@material-ui/lab/AlertTitle'

Importing Alert in Material UI v5

With the release of Material UI v5, Alert and AlertTitle were moved to @mui/material. Now, you can import them directly from the core package.

Install Material UI v5 (if not already installed)

npm install @mui/material @emotion/react @emotion/styled
# or
yarn add @mui/material @emotion/react @emotion/styled

Import Components

import Alert from '@mui/material/Alert'
import AlertTitle from '@mui/material/AlertTitle'

Example: Using Alert Inside Snackbar

Here’s a simple example of using Alert inside a Snackbar component in Material UI v5:

import React, { useState } from 'react'
import Snackbar from '@mui/material/Snackbar'
import Alert from '@mui/material/Alert'
import AlertTitle from '@mui/material/AlertTitle'
import Button from '@mui/material/Button'

const AlertSnackbar = () => {
  const [open, setOpen] = useState(false)

  return (
    <div>
      <Button variant="contained" onClick={() => setOpen(true)}>
        Show Alert
      </Button>
      <Snackbar open={open} autoHideDuration={6000} onClose={() => setOpen(false)}>
        <Alert severity="error" onClose={() => setOpen(false)}>
          <AlertTitle>Error</AlertTitle>
          This is an error alert — check it out!
        </Alert>
      </Snackbar>
    </div>
  )
}

export default AlertSnackbar

FAQs

1. Why am I getting an error when importing Alert from @material-ui/core?

Alert was never part of @material-ui/core in v4. It was inside @material-ui/lab. In v5, it moved to @mui/material. Make sure you are importing it correctly based on your version.

2. How do I check which version of Material UI I am using?

Run the following command in your project folder:

npm list @mui/material @material-ui/core @material-ui/lab

If you see @mui/material, you are using v5. If you see @material-ui/core, you are on v4.

3. Do I need @emotion/react and @emotion/styled for Material UI v5?

Yes, Material UI v5 uses Emotion for styling, so you need to install these dependencies.

4. How do I migrate from Material UI v4 to v5?

Follow the official MUI migration guide.