Milan Poudel
Milan Poudel

Reputation: 792

How can I pass default theme that is provided by MUI5 and create a style for any component in MUI5?

import { styled } from "@mui/system";
import { CardTravel, Home, People } from "@mui/icons-material";
import { Box, Container, Typography } from "@mui/material";
import React from "react";

const BoxContainer = styled(Box)(({ theme }) => ({
  display: "flex",
  marginBottom: theme.spacing(4),
  [theme.breakpoints.up("sm")]: {
    marginBottom: theme.spacing(3),
    cursor: "pointer",
  },
}));

const TextContainer = styled(Typography)(({ theme }) => ({
  [theme.breakpoints.down("sm")]: {
    display: "none",
  },
}));

const styles = {   //here how can I use theme here  and pass it
  iconStyles: {
    marginRight: 2,
[theme.breakpoints.up("sm"): { //so I can use here for breakpoints or anything
display: "none", 
  },
};

const Leftbar = () => {
  return (
    <Container
      sx={{
        paddingTop: 2,
        height: "100vh",
        bgcolor: { sm: "white", xs: "primary.main" },
        color: { sm: "#555", xs: "white" },
        border: { sm: "1px solid #ece7e7" },
      }}
    >
      <BoxContainer>
        <Home sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <People sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <CardTravel sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
      <BoxContainer>
        <Home sx={styles.iconStyles} />
        <TextContainer>HomePage</TextContainer>
      </BoxContainer>
    </Container>
  );
};

export default Leftbar;

Here, in my code all my icons are different but their css properties will be same. I can't use styled() because they all are different icons. I am trying to define custom styles and trying to pass it with "sx" by defining as styles.iconStyles. How can I use theme in that code ?

Upvotes: 2

Views: 4194

Answers (1)

Gray Singh
Gray Singh

Reputation: 310

In index.js, you import createTheme and ThemeProvider. You can create your customize your theme using createTheme and enclose ThemeProvider on the <App/>

import { createTheme, ThemeProvider } from "@mui/material/styles";

const theme = createTheme({
  palette: {
    primary: {
      main: orange[500]
    },
    secondary: {
      main: red[500]
    }
  }
});

<ThemeProvider theme={theme}>
      <App />
</ThemeProvider>

Create your own component and get the color from theme you declared like this one

const SearchDiv = styled("div", {
  shouldForwardProp: (props) => true
})(({ theme, open }) => ({
  display: "flex",
  alignItems: "center",
  backgroundColor: theme.palette.secondary.main,
  width: "50%",
  [theme.breakpoints.down("sm")]: {
    display: open ? "flex" : "none"
  }
}));

Check here for the codesandbox: SEE THIS

Upvotes: 1

Related Questions