'Material UI: "styled" child component not applying css rules
I'm having an issue where I'm using the styled function to style a custom React component but the styles are not being applied. In the example below, I would expect the Child component to have the color: red style, but it doesn't. The sibling component, however, is styled correctly.
import "./styles.css";
import { Child } from "./Child";
import { Typography } from "@mui/material";
import { styled } from "@mui/material/styles";
const StyledChild = styled(Child)(() => ({
color: "red"
}));
const StyledSibling = styled(Typography)(() => ({
color: "blue"
}));
export default function App() {
return (
<>
<StyledChild />
<StyledSibling>Sibling</StyledSibling>
</>
);
}
import { Typography } from "@mui/material";
import { FunctionComponent } from "react";
export const Child: FunctionComponent = () => {
return <Typography>Child</Typography>;
};
Solution 1:[1]
styled causes a className prop to be passed to the wrapped component, but Child isn't passing the className prop along to Typography.
Here's an example of how to fix Child.tsx:
import { Typography } from "@mui/material";
import { FunctionComponent } from "react";
export const Child: FunctionComponent<{ className?: string }> = ({
className
}) => {
return <Typography className={className}>Child</Typography>;
};
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 | Ryan Cogswell |
