Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>;
};

CodeSandbox

like image 755
Sean Owens Avatar asked Aug 10 '26 04:08

Sean Owens


1 Answers

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>;
};

Edit elastic-mayer-yr131s

like image 93
Ryan Cogswell Avatar answered Aug 13 '26 10:08

Ryan Cogswell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!