1
votes

I need a way to create classes without styled nor css method.

Lets assume proper style system with components having only basic styles, but not positioning, margin etc.

e.g.

const Root = styled.div`/* Some styles */`

export const MyComponent = ({className}) => <Root className={className} />

So this is easy, I attach private styles for component and I allow it to receive and apply class from parent.

If I have "classic" css, I would use it like this

import styles from 'some-styles.module.css';

...

<MyComponent className={styles.someStyle} />

Which will work as expected.

Here is the problem:

How do I create a class with styled-components only? It was working with Glamorous once, but SC (and Emotion) is not returning class name from css.

I can't use separate css files just to allow this styling, which should be common use case (parent setting size of children)

Edit & solution in Emotion

I figured out that Emotion adds extra property css which is available for every jsx element. It can be used to native <div>, styled <Div> or custom React component <MyComponent. Babel is changing css attribute with css({...}) to className during compilation. If <MyComponent> only accepts prop className it will receive it from parent via css prop.

1
Not sure if I got it right, but you want to use styled components to generate only the className and not a component? - Vencovsky
styled-components make className an implementation detail. You should not work with classNames directly when using styled-components. This question is XY problem. - marzelin
@Vencovsky, yes, I use both. - Łukasz Ostrowski
@marzelin I understand, however I still belive I should be able to somehow pass styles from parent to child. How to achieve this other way? I can try passing css, not sure if it will work though. Is it implementation detail... I dont think I agree. Yes, SC use them under the hood, but this is still a web api standard, so it should have flexible api to work with it (and it does, somehow), I just need a way to get access for its creation. Emotion has <Classnames util for that - Łukasz Ostrowski

1 Answers

0
votes

I still belive I should be able to somehow pass styles from parent to child.

There is a way to do that, but no exactly the way you want to do.

In react js (you can't do this in React Native yet), you can pass the child component inside the parent style and it will add the style in the child when it's wrapped by the parent.

e.g.

const ParentComponent = styled.div`
    ${ChildComponent} {
         /* Child css*/
    }
`

Sorry if formatting is bad, I'm on mobile