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

1

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

4 Comments

WHHAAAAAA???? You guys made this library too easy to use 🔥👌💥 Thank you for all of the effort you put into it.
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 {...}
SUPER IMPORTANT: There is a space between the & and the .react-datepicker this is crucial for this answer to work as expected.
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.
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>

Comments

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.