deni rachmadi
deni rachmadi

Reputation: 31

how to attach styled-component style to a component className props?

hi guys i've create a react component. in react way i could easily attach css style to my component via className="some_style"

but how do i attach my styled component to these className props.

say per as

<Component className="styled_component" />

i don't know which approach im gonna use ? Thanks

Upvotes: 2

Views: 3544

Answers (3)

Yassine S.
Yassine S.

Reputation: 1069

This usually works well for me (even if hilariously I actually found this question cause I'm having trouble with a specific situation using className):

const Component = styled.div.attrs({
  className: '[add your classes here]'
})

Upvotes: 3

Oscar W
Oscar W

Reputation: 484

When using styled-components, you don't have to use the className prop on your components anymore. Let's say you've got a div that you want to style. First declare the div as a styled-component.

const StyledDiv = styled.div`
   background-color: blue;
`

Notice how I'm using styled.div as it's a div element I'm using. Then to render this componenet, you do the same as you would with any other component.

return(
   <StyledDiv />
)

The div will then render with the css you applied to it, you don't have to interact with className.

Upvotes: -1

Sudipto Roy
Sudipto Roy

Reputation: 1046

Well you can't because you don't know which classname will your css-in-js gets compiled to. Styled component helps you write the CSS of a particular component in JS. You can try writing the CSS of <Component /> in Component.js file. If the CSS class is reuseable, create a common CSS file and include it in index.js/App.js

Upvotes: 0

Related Questions