Home > OS >  ReactJS: How to pass props on styled material-UI v5xx?
ReactJS: How to pass props on styled material-UI v5xx?

Time:01-27

Since useStyle() does not work on my material-UI v5xx (can somebody explain why?) , I was confused about how to pass props on this version.

for example for Material-UI v4 we can simply type like this:

const Navbar = () => {
  const [open, setOpen] = useState(false);
  const classes=useStyles({open});
  return(....);
}

but for v5 I only can use Styled() instead of useStyle(), so im confused about this part, I want to make a button that display search bar, so I have created like this:

const theme = createTheme({
  palette: {
    primary: {
      main: "#FFE162",
      contrastText: "black",
    },
  },
});

// in this part i want my open function work
const StyleSearch = styled("div")(({ theme })() => ({
  display: "flex",
  alignItems: "center",
  backgroundColor: alpha(theme.palette.common.white, 0.4),
  "&:hover": {
    backgroundColor: alpha(theme.palette.common.white, 0.6),
  },
  borderRadius: theme.shape.borderRadius,
  width: "50%",
  [theme.breakpoints.down("sm")]: {
    display: (props) => (props.open ? "flex" : "none"),
  },
}));

const Navbar = () => {
  const [open, setOpen] = useState(false);
  function handleOpen() {
    setOpen(true);
  }
  return( 
      <...>
        <StyleSearchBtn onClick={handleOpen} />);
      <.../>
}

as you can see the open is not set how do pass that to the props.

CodePudding user response:

It's not compatible with the new version of React, as you can check on their documentation

⚠️ @mui/styles is the legacy styling solution for MUI. It is deprecated in v5. It depends on JSS as a styling solution, which is not used in the @mui/material anymore. If you don't want to have both emotion & JSS in your bundle, please refer to the @mui/system documentation which is the recommended alternative.

⚠️ @mui/styles is not compatible with React.StrictMode or React 18.

Here you have the documentation needed to use styled() correctly.

For your example, you can pass the props normally, like:

<StyleSearch props={theme, open} />

or

<StyleSearch open={open} theme={theme} {...props} />
  •  Tags:  
  • Related