can't get @mui 5 styled components to work
I'm following the tutorial on mui's website to get the version 5 of the framework in place. Everything is fine except that I cannot figure out how to make the styled components work.
Here is a minimal example with a sandbox to try it out:
import React from "react";
import { render } from "react-dom";
import { createTheme, styled, ThemeProvider } from "@mui/material/styles";
import { Button } from "@mui/material";
const theme = createTheme({
palette: {
primary: {
main: "#4cfcb3",
light: "#8affe5",
dark: "#00c883",
contrastText: "#000"
},
secondary: {
main: "#00b0ff",
light: "#69e2ff",
dark: "#0081cb",
contrastText: "#FFF"
}
}
});
const Test = styled(() => <div>TEST SHOULD BE RED</div>)({
color: "red",
backgroundColor: "#000"
});
const App = () => (
<ThemeProvider theme={theme}>
<Button color="primary" variant="contained">
Hello Button
</Button>
<br />
<br />
<Test />
</ThemeProvider>
);
render(<App />, document.getElementById("app"));
In this example, we can see that the button correctly gets the colors as specified in the theme, so that.s good, but my Test
styled component isn't styled at all as you can see here:
What am I doing wrong?
Solution 1:
You have to call it like this:
Basically you have to remove your callback and only pass it the 'div'
, and a config object with the CSS properties.
To call it use the opening and closing tag of the component.
import React from "react";
import { render } from "react-dom";
import { createTheme, styled, ThemeProvider } from "@mui/material/styles";
import { Button } from "@mui/material";
const theme = createTheme({
palette: {
primary: {
main: "#4cfcb3",
light: "#8affe5",
dark: "#00c883",
contrastText: "#000"
},
secondary: {
main: "#00b0ff",
light: "#69e2ff",
dark: "#0081cb",
contrastText: "#FFF"
}
}
});
const Test = styled('div')({
color: "red",
backgroundColor: "#000"
});
const App = () => (
<ThemeProvider theme={theme}>
<Button color="primary" variant="contained">
Hello Button
</Button>
<br />
<br />
<Test>TEST SHOULD BE RED</Test>
</ThemeProvider>
);
render(<App />, document.getElementById("app"));
Solution 2:
You can replace this code to make it work
const Test = styled("div")(() => ({
color: "red",
backgroundColor: "#000"
}));
and inside your App component you can you use it with that form
<Test>This is red </Test>
Explanation
If you want to styled a html element like <div>
or <p>
you need to do wrap it with ""
.
const StyledDiv = styled("div")(() => ({ some attributes }))
or if you want to style a Material UI component (for example then you can use it like this
const StyledButton = styled(Button)(() => ({ some attributes }))