mui / material-ui

Material UI: Comprehensive React component library that implements Google's Material Design. Free forever.
https://mui.com/material-ui/
MIT License
93.81k stars 32.25k forks source link

[system] Use components as selectors with styled() #40641

Closed CharlineCouchot closed 9 months ago

CharlineCouchot commented 9 months ago

Duplicates

Summary

Following the documentation on the Components Selector API, using a regular styled component as a selector works but it is not possible to use MUI components as selectors.

Examples

https://codesandbox.io/p/devbox/peaceful-ptolemy-ytqqgt

import { styled } from "@mui/joy/styles";
import { Typography } from "@mui/joy";
import { css } from "@mui/system";
import "./App.css";

const Child = styled("div")(css`
  color: red;
`);

const Parent = styled("div")(
  () => css`
    ${Child} { /* This works */
      color: green;
    }

    ${Typography} { /* This breaks the component */
      color: blue;
    }
  `,
);

function App() {
  return (
    <div>
      <Parent>
        <Child>Green because I am inside a Parent</Child>
        <Typography>I should be blue because I am inside a Parent</Typography>
      </Parent>
      <Child>Red because I am not inside a Parent</Child>
      <Typography>Not blue because I am not inside a Parent</Typography>
    </div>
  );
}

export default App;

Motivation

Maybe I'm doing something wrong, but with this approach, MUI components should behave the same way other styled components do IMO.

Search keywords:

ANUGLYPLUGIN commented 9 months ago

@CharlineCouchot

const Parent = styled("div")( () => css` ${Child} { color: green; }

${Typography} {
  color: blue;
}

`, );


- The emotion react supports emotion component nested selectors, so you just need to wrap customer React Element with it.
![image](https://github.com/mui/material-ui/assets/97073795/fbbd5d14-cdce-4af5-9750-302150688209)
CharlineCouchot commented 9 months ago

That solved it! Thank you :) Would suggest maybe adding that to the Components Selector API documentation?

ANUGLYPLUGIN commented 9 months ago

That solved it! Thank you :) Would suggest maybe adding that to the Components Selector API documentation?

I am not sure about that because styled function is powered by @emotion/styled. Probably we can give it to owner .

ZeeshanTamboli commented 9 months ago

Would suggest maybe adding that to the Components Selector API documentation?

Maybe not. The exported MUI components aren't wrapped with the styled API, so it might not be necessary to add it to the Components Selector API documentation.