Home > Software design >  Unexpected Snackbar Alert behavior
Unexpected Snackbar Alert behavior

Time:12-22

Why is this throwing an error:

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
const Alert = ({children}) => <MuiAlert>{children}</MuiAlert>

<Snackbar open>
    <Alert>test</Alert>
</Snackbar>

(but this is not?)

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";

<Snackbar open>
    <MuiAlert>test</MuiAlert>
</Snackbar>

In my understanding, they should both work the same.

CodePudding user response:

When you're using single line component syntax, you don't need to use return keyword for getting back the component. Just => is enough:

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
const Alert = ({children}) => <MuiAlert>{children}</MuiAlert>

export default function App() {
  return (
    <>
      <Snackbar open>
        <Alert>test</Alert>
      </Snackbar>
    </>
  );
}

CodePudding user response:

It turns out I needed to pass the ref using React.forwardRef to the Alert:

import Snackbar from "@mui/material/Snackbar";
import MuiAlert from "@mui/material/Alert";
const Alert = React.forwardRef(({children}, ref) => <MuiAlert ref={ref}>{children}</MuiAlert>)

<Snackbar open>
    <Alert>test</Alert>
</Snackbar>
  • Related