'How to create custom CSS classes using MUI v5 theme?
I am using MUI v5 in my application along with react-d3-tree
which renders SVG tree charts. It offers an API to include custom CSS class names in the <path>
elements linking the tree nodes to one another. I would like to pass custom class names to react-d3-tree
and be able to use MUI's theme variables. Thus simply importing a .css
file will not be enough.
How can I create statically named custom CSS classes using MUI v5 and take advantage of the MUI theme definition that styles other parts of my app?
Solution 1:[1]
There is the https://mui.com/api/global-styles/ component.
Usage:
return (
<>
<GlobalStyles
styles={(theme) => ({
h1: { color: theme.palette.primary.main },
h2: { color: "green" },
".some-class": { backgroundColor: "lightpink" }
})}
/>
<h1>This is a h1 element</h1>
<h2>This is a h2 element</h2>
<button className="some-class">Pink</button>
</>
);
Solution 2:[2]
One way to locally define a class and reuse it is to define the css class at a sx
property of a parent component, like in the following example:
function Child({ message, className }) {
return <Typography className={className}>{message}</Typography>;
}
function Parent() {
return (
<Box
sx={{
'.childClass': {
color: 'primary.main'
}
}}
>
<Child message="Child with no css class defined" />
<Child className="childClass" message="Child with css class defined" />
</Box>
);
}
In this example, 'primary.main'
resolves to theme.pallete.primary.main
, as mentioned here.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yozi |
Solution 2 | Crferreira |