Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Classes to Styled Component

I am trying to add class names to a React Component to make it easier for me to customize that component using Styled Components. Here is a simplified outline of the component:

const SignupForm = props => (
    <form>
      <Input className="input" />
      <Button className="button" />
    </form>
  )

And here is how I would like to use it:

import { SignupForm } from '../path/to/signup-form'

  <Form />
...

const Form = styled(SignupForm)`
  .input {
     /* Custom Styles */
  }

  .button {
     /* Custom Styles */
  }
`

However, this does not work. Only if I create a wrapper Component will it work - like this:

import { SignupForm } from '../path/to/signup-form'

  <FormWrapper>
    <SignupForm/>
  <FormWrapper>
...

const FormWrapper = styled.div`
  .input {
     /* Custom Styles */
  }

  .button {
     /* Custom Styles */
  }
`

I'm wondering whether or not there is a way to access the .input and .button classes without having to create a wrapper class, i.e. via the actual imported class itself? If so, how?

like image 711
Moshe Avatar asked Jan 15 '20 17:01

Moshe


People also ask

Can I use classes in styled-components?

Adding a persistent CSS className to your styled components can make it easier for end users of your website to take advantage of user stylesheets for accessibility. An end user of your site could then write their own CSS styles matching HTML elements using a class name of . container .

Can I use CSS with styled-components?

You can use standard CSS properties, and styled components will add vendor prefixes should they be needed. Styled components are independent of each other, and you do not have to worry about their names because the library handles that for you.


1 Answers

You need to provide className for the wrapper/container as styled-component injecting the styles through it:

const SignupForm = ({ className }) => (
  <form className={className}>
    <input className="input" />
    <button className="button">Button</button>
  </form>
);

const Form = styled(SignupForm)`
  .input {
    background-color: palegreen;
  }

  .button {
    background-color: palevioletred;
  }
`;

Edit hungry-moser-3lu0p

like image 145
Dennis Vash Avatar answered Oct 05 '22 11:10

Dennis Vash