Skip to content

Override child component styles (API suggestion) #139

Open

Description

@elado

Let's say I have a <MyComponent> and <MyList> that contains a list of <MyComponent>.

Only when in under <MyList>, I want <MyComponent> to have some different styles, maybe flex, or a different background-color. flex is a good example because MyList may have display: flex and might want its children to have flex: 25% and also stretch vertically.

Currently it doesn't seem like I can override <MyComponent> that is nested under <MyList>, as I would with regular css.

Here's a suggestion (I posted in https://github.com/gajus/react-css-modules/issues/94 but it might make more sense here):

// MyComponent.scss
.component {
  background-color: yellow;
  font-weight: bold;
}

// MyList.scss
.list {
  // ...
}

.listItem {
  border: 1px solid blue;
}

.listItem {
  // ▼ this will generate ".listItem_[hash] .component_[hash] {}" rule instead of just .listItem_[hash]
  override-child: component from './MyComponent.scss';
  background-color: red;
}
// MyComponent.jsx
import styles from './MyComponent.scss'
export default ({ title }) => <div className={styles.component}>{title}</div>

// MyList.jsx
import styles from './MyList.scss'
export default ({ titles }) => (
  <div className={styles.list}>
    {titles.map(title => <div key={title} className={styles.listItem}><MyComponent title={title} /></div>)}
  </div>
)

And ideally that would work in all hierarchies. If I have <MyButton> in MyComponent, I can affect if from .MyList.scss:

.listItem {
  // ▼ this will generate ".listItem_[hash] .component_[hash] .button_[hash] {}" rule
  override-child:
    component from './MyComponent.scss',
    button from './MyButton.scss';
  font-size: 17px;
}

I read the suggestions by @joeybaker here: #21 (comment) but I think there should be a better way.

Thoughts?

Activity

  1. liady commented on Apr 19, 2016

    @liady

    @elado +1 that's a very good idea. The reference can even be in the selector level:

    /* MyList.scss */
    .listItem :external(button from './MyButton.scss') {
      font-size: 17px;
    }
    /* this will generate ".listItem_[hash] .button_[hash] {}" rule */

    And that way even the child element can have a specific rule for when it is inside a container:

    /* MyButton.scss */
    :external(listItem from './List.scss') .button {
      font-size: 17px;
    }
    /* this will generate ".listItem_[hash] .button_[hash] {}" rule */
  2. sohkai commented on Apr 19, 2016

    @sohkai

    @elado So you can accomplish your first example right now if you allow your MyComponent to take in a classname (or entire style object) as a prop and apply it on itself, and then in MyList, create a class that composes the class from MyComponent with the override and then pass the new class back to MyComponent. This is essentially what @joeybaker suggested as approach 2:

    // MyComponent.scss
    .component {
      background-color: yellow;
      font-weight: bold;
    }
    
    // MyList.scss
    .listItemChild {
      composes: component from './MyComponent.scss';
      background-color: red;
    }
    // MyComponent.jsx
    import styles from './MyComponent.scss'
    export default ({ className, title }) => (
        <div className={className ? className : styles.component}>{title}</div>
    );
    
    // MyList.jsx
    import styles from './MyList.scss'
    export default ({ titles }) => (
      <div>
        {titles.map(title => (
            <div key={title}>
                <MyComponent className={styles.listItemChild} title={title} />
            </div>
        ))}
      </div>
    );

    Not that I dislike what you're proposing, since it would certainly be convenient at times, but on some level I do feel like this kind of goes against some of the things that CSS modules was designed to protect you from. Although it's always on the user to responsibly use the provided tools, allowing for child overrides would get us closer to the messy world of normal CSS's spaghetti overrides.

    It's a little more complicated, but in something like your case with flexbox, or specific style overrides, what if you made a base component that had the common styles and then put a shim component around the base component that added the positional / spacing styles, or any other specific style overrides with the class names approach above? If necessary, the shim component could also be made more generic with props. Alternatively, sometimes these overrides are because of theming (ie. override colors and whatnot) and maybe building functionality (such as HOCs in React) to switch between themes would be more idiomatic.

  3. elado commented on Apr 19, 2016

    @elado
    Author

    @sohkai with your example, imagine a little more complex situation where there's a logic on which class to give based on a prop.

    // MyComponent.jsx
    import styles from './MyComponent.scss'
    export default ({ title, isMinimized }) => {
        const className = isMinimized ? styles.minimized : styles.normal
        return <div className={className}>{title}</div>
    }

    I don't want to replicate the isMinimized logic to the MyList or any other container of MyComponent. It could be a little more complex if multiple variants are involved.

    This is a real-world example from a GChat style chat windows I'm building.

    X doesn't produce bad code. Bad developers do.

  4. sohkai commented on Apr 19, 2016

    @sohkai

    @elado With multiple classes like that, I'm currently using react-css-modules to provide a new style object that's been generated with sass mixins to get the necessary compositions in containing components. It's not ideal, I know.

    I'm just afraid that if something like this is provided, a lot of people are going to be tempted to take the easy way out when they start using CSS modules and end up with stylesheets that are more or less as messy as they would've been as a normal stylesheet. It's kind of like !important; we know we shouldn't use it, but invariably, someone will and someone else is going to have to maintain their work. Maybe it'd be nice to have this functionality provided as a seperate postcss plugin that builds on top of the core plugin so you can opt into it if you'd like.

  5. elado commented on Apr 19, 2016

    @elado
    Author

    @sohkai I wouldn't say completely it's like !important or the way spaghetti css is today, because css-modules already teaches developers how to think in modules (which is great) and also the reference of the class overridden is explicitly written, so it's clear where things come from.

    Even a separate postcss plugin is great. I'd be happy to help/test (not familiar with postcss ecosystem too much yet).

  6. panuhorsmalahti commented on Aug 16, 2017

    @panuhorsmalahti

    Overriding styles from parent components is not messy if the child component explicitly defines which styles are allowed to be overridden. For an example of how this can be accomplished in practice, see e.g. the Polymer framework.

  7. samends commented on Jun 24, 2019

    @samends

    I agree with @panuhorsmalahti and wanted to bump this as I had an example of this currently. I'm trying to override a style created by google material:

    .dialog {
    	composes: mdc-dialog__surface from '@material/dialog/dist/mdc.dialog.css';
    	max-width: 100%;
    }
    

    However I can't do this without a !important on max-width. This dirties the code base and forces developers to use worst practices.

  8. adamreisnz commented on Oct 8, 2020

    @adamreisnz

    @sohkai how would you solve the use case with your approach when the parent component cannot directly apply another class on the child component? E.g. when using <slot /> inside the parent component.

    For example, consider this simplified group component:

    <template>
      <div :class="$style.group">
        <label
          :class="{
            [$style.label]: true,
            [$style.labelError]: hasError,
          }"
        >
          {{label}}
        </label>
        <slot/>
      </div>
    </template>
    

    And then using it as follows:

    <group label="Name" :validation="$v.model.name">
      <form-input name="name"/>
    </group>
    

    I would like the group component, which is aware of any errors and validation to be able to override styles of the child components that are passed into its slot. As far as I know and have tried, I cannot apply classes on the <slot> element itself (they are not propagated).

    So there doesn't seem to be a clean way to apply an error class on the <form-input> component through the parent <group> component.

    The only workaround I can see would be to switch back to scoped or global styles, or to have to pass validations to the <form-input> component as well, which would be a bit redundant.

  9. JasonTheAdams commented on Mar 3, 2022

    @JasonTheAdams

    Just ran into this myself when using a 3rd party component. I'm able to apply a class on the top-level node in the component, but I can't target any of the child nodes being rendered. Having a way around this would be useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions