Search code examples
styled-components

How to change the css on a component using styled-components


My boilerplate comes with the styled-components module. Here's another component:

return (
  <form onSubmit={this.handleFormSubmit}>
    <PlacesAutocomplete inputProps={inputProps} />
    <button type="submit">Submit</button>
  </form>
)

I just want to add css to this thing, but I can't. So I guess I'll learn the react way of doing it... but after 2 days of google I still have no idea how to style this, and the input box is literally invisible by default. How do I modify a component (in this case Google-Places-Autocomplete) in my npm modules folder with styled-components?

  • className doesn't work
  • I have no idea if it's even possible to specify properties to the < PlacesAutocomplete>'s input if it's buried within the component, within npm modules

Solution

  • Please see the documentation and guides: https://www.styled-components.com/docs/basics

    styled-components uses a different approach to styling components than the old-school CSS does. Taken from React, styled-components focuses on styling encapsulated elements instead of the whole page (ideally, your styled component should never know about and be influenced by the parent/context in which it is placed).

    From the practical point of view, I hope these two pages will explain clearly how you can style your components in an easy way (see code samples):

    https://www.styled-components.com/docs/basics#styling-any-components

    https://www.styled-components.com/docs/faqs#can-i-nest-rules

    While you may not always be able to use className on a third-party component, you can always use style cascading:

    const MyAutoCompleteWrapper = styled.div`
        & > .google-places-autocomplete {
            font-size: 24px;
            color: rgb(255, 0, 0);
        }
    `;
    
    React.render(
      <MyAutoCompleteWrapper>
        <PlacesAutocomplete inputProps={inputProps} />
      </MyAutoCompleteWrapper>,
      document.querySelector('.app')
    );
    

    Also it may be useful to remember that using styled-components does not stop you from using normal CSS globally, if that is your preference. You may still simply attach a separate CSS stylesheet that styles the third-party component in the way you need it, and it should work just fine 🙂