Target specific CSS classes with Styled Components
Asked Answered
M

3

11

How would I go about styling something like the react-datepicker with styled-components? The datepicker library looks like it uses some type of BEM style (screenshot below) which I would normally just use their provided class names and style those using Sass. But, how would I target those class names with styled-components? Is that even possible?

enter image description here

Metalinguistics answered 25/7, 2017 at 11:9 Comment(1)
Please don't post code, exceptions, or results as images. They can't be copied (partly) for answering and their "text" won't appear in search engines. Images should only be used as a last resort. – Evulsion
P
18

Since styled-components is just CSSβ„’ you'd do it like with any other style sheet, by using the class names react-datepicker provided.

The only difference is that you'll have to wrap the datepicker in one wrapper styled component which applies all of these classes:

const Wrapper = styled.div`
  &.react-datepicker {
    color: blue;
  }
`

<Wrapper>
  <Datepicker />
</Wrapper>
Paving answered 25/7, 2017 at 21:20 Comment(4)
WHHAAAAAA???? You guys made this library too easy to use πŸ”₯πŸ‘ŒπŸ’₯ Thank you for all of the effort you put into it. – Metalinguistics
I'm bumping up against the same issue. This mostly worked for me, except I couldn't use the &, my selector had to just be along the lines of .react-datepicker {...} – Corlisscorly
SUPER IMPORTANT: There is a space between the & and the .react-datepicker this is crucial for this answer to work as expected. – Gale
I've rolled back an edit that appears to meaningfully change this answer to the same solution provided by another answer. If it was in fact a typo, please feel free to re-correct it. – Etymology
A
8

Searching for hours, I found that the best solution is to add a stylized parent component (it can be a div) overlying the component that needs a className and add the definition of the className directly into the stylized parent component.

VERY IMPORTANT:
A space is needed between the ampersand & and the class for this to take effect!

const StyledParent = styled.div`
   & .your-class-name {
     border-color: red;
   }
`;

<StyledParent>
   <Datepicker yourClassName="your-class-name" />
</StyledParent>
Analiese answered 11/11, 2020 at 20:37 Comment(0)
E
0

If you ever need to access and style another component you can do this if they are not in the same file:

Export whatever you need to access:

export { Wrapper as CircledButtonWrapper };

Import it where you need it:

import { CircledButtonWrapper } from "/Bla/CircledButton";

Use it where you need to style it:

const Wrapper = styled.div` 
 /* Some other styles */
    &:hover {
        ${CircledButtonWrapper} {
            opacity: 1;
        }
    } `;

Edit: I see now that the question was refering to accessing className...

Edmiston answered 23/12, 2022 at 14:13 Comment(0)

© 2022 - 2024 β€” McMap. All rights reserved.