6

How can disable the alert, I didn't find a boolean parameter for this in the documentation.

import React from 'react';
import Alert from '@material-ui/lab/Alert';

export default function SimpleAlerts() {
  const classes = useStyles();

  return (
    <div>
      <Alert severity="error">This is an error alert — check it out!</Alert>
    </div>
  );
}
problème0123
  • 841
  • 2
  • 9
  • 23

3 Answers3

7

Use conditional rendering:

import React from 'react';
import Alert from '@material-ui/lab/Alert';

export default function SimpleAlerts() {
  const classes = useStyles();

  return (
    <div>
      {someCondition && <Alert severity="error">This is an error alert — check it out!</Alert>}
    </div>
  );
}
MorKadosh
  • 5,846
  • 3
  • 25
  • 37
1

You could wrap it in a <Snackbar> (doc)

const [open, setOpen] = React.useState(true)

const handleClick = () => {
  setOpen(!open)
}

return (
  <>
    <Button variant="outlined" onClick={handleClick}>
      Toggle
    </Button>
    <Snackbar open={open}>
      <Alert severity="success">This is a success message!</Alert>
    </Snackbar>
  </>
)

Codesanbox for demo

Edit Material demo (forked)

hgb123
  • 13,869
  • 3
  • 20
  • 38
0
import Alert from "@mui/material/Alert";
import Snackbar from "@mui/material/Snackbar";


// jsx to return inside the component
return (
    // snackbar is responsible for the position for the Alert
    <Snackbar 
      // define location
      anchorOrigin={{ vertical: "bottom", horizontal: "center" }}
      // open and onClose needs boolean. you can set inside useState
      open={showAlert}
      onClose={closeAlert}
      // after 6 seconds it will automatically close
      autoHideDuration={6000}
    >
      <Alert severity="info">{contextHere}</Alert>
    </Snackbar>
  );
Yilmaz
  • 35,338
  • 10
  • 157
  • 202