Source:  Twitter logo

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?

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;
  }
`;

30 users liked answer #0dislike answer #030
Dennis Vash profile pic
Dennis Vash

Just add extra atrribute className by using attrs to existing styled component.

const FormWrapper = styled.div.attrs({
  className: 'SignupForm',
  })`
    .input {
    /* Custom Styles */
    }

   .button {
   /* Custom Styles */
   }
   `
2 users liked answer #1dislike answer #12
Ashwani Panwar profile pic
Ashwani Panwar

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).