Styled Components / React – Style on external element

All we need is an easy explanation of the problem, so here it is.

I’m using Material UI components and MaterialTable and I want to stylish the components using StyledComponents

But I not been having the desired results when I try to apply styles using StyledComponents

CodeSandBox Online Example

Example:

import styled from 'styled-components'
import MaterialTable from "material-table";

export const MaterialTableStyled = styled(MaterialTable)`
    /* STYLE FOR FILTER ROW */
    tbody > .MuiTableRow-root:first-child {
        background-color: #F1F3F4 !important;
    }
`

When I use the MaterialTableStyled component no applied the style.

Instead, if I use a div on my StyledComponent:

import styled from 'styled-components'

export const MaterialTableStyled = styled.div`
    /* STYLE FOR FILTER ROW */
    tbody > .MuiTableRow-root:first-child {
        background-color: #F1F3F4 !important;
    }
`

My custom styles work perfecty on that way:

<MaterialTableStyled> // DIV WITH STYLES
    <MaterialTable
        // ALL PROPS AND STUFFS
    />
</MaterialTableStyled>

…the question is: it’s possible “override” or change styles without using the div to change the style?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

A component has to pass the className property into their children in order styled function to work.

From a quick look, MaterialTable doesn’t do that, as a result styled components can’t assign another css class to the table.

Component compatible with styled function

const StyledFriendlyComp = ({className}) => <div className={className}>Styles being applied</div>

Component that won’t work with styled function

const StyledFriendlyComp = () => <div>Styles not working</div>

In this cases you need to wrap the component with another element like div.

Method 2

If you want to style a component directly, you will need to specify a HTML element.

In your case though (if you are only using it to style lower-level components) you could use something like React Context to pass down a prop that the styled-component can consume and utilize to determine the style.

If you explicitly need the prop/value for styled-component usage, you could also use set it as a styled-component transient prop.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply