styled-components / babel-plugin-styled-components

Improve the debugging experience and add server-side rendering support to styled-components
MIT License
1.07k stars 140 forks source link

css props does not work when the component come from a props #201

Open kopax opened 5 years ago

kopax commented 5 years ago

css does not work

I have the following app with a non ejected create react app:

import { Fragment, PureComponent } from 'react';
import { withTheme } from 'styled-components';
import { css } from 'styled-components';
import H5 from '@bootstrap-styled/v4/lib/H5';
import Ul from '@bootstrap-styled/v4/lib/Ul';
import Li from '@bootstrap-styled/v4/lib/Li';
import React from 'react';

class ServiceItem extends PureComponent {
  render() {
    const { icon: Icon, list, title } = this.props;
    return (
      <div>
        {<Icon className="w-25" css={css`${(props) => `fill: ${props.theme['$brand-primary']};`}`} />}
        <H5>{title}</H5>
        {list.length > 0 && (<Ul>{list.map((item) => <Li key={item}>{item}</Li>)}</Ul>)}
      </div>
    );
  }
}

export default withTheme(ServiceItem);

Expect

To have a valid synthax

Result

×
ReferenceError: Icon is not defined
Module../src/containers/HomePage/components/ServicesAndSolutions/ServiceItem.js
src/containers/HomePage/components/ServicesAndSolutions/ServiceItem.js:14
  11 | const { icon: Icon, list, title } = this.props;
  12 | return (
  13 |   <div>
> 14 |     {Icon && <Icon className="w-25" css={css`${(props) => `fill: ${props.theme['$brand-primary']};`}`} />}
     | ^  15 |     <H5>{title}</H5>
  16 |     {list.length > 0 && (<Ul>{list.map((item) => <Li key={item}>{item}</Li>)}</Ul>)}
  17 |   </div>

Even if the class is not instanciated anywhere in the code, it will crash.

Versions

kopax commented 5 years ago

Beside that, I have a question regarding css props.

I am using css={csscolor: red;} and not css={'color: red;}, every where in my code, while in the documentation they do not say to use it.

I thought it was supposed to be used, I've seen that when the css props was released in some source code.

What is the css util for then? I can notice that without it, my IDE (IntelliJ) lose the synthax coloration.

satya164 commented 5 years ago

202

quantizor commented 5 years ago

Because of how the css prop transpiler works I don't think we'll ever be able to support this. The css prop dynamically generates a new component, which is injected into the global scope. Up there the prop isn't available as a variable so that's why you're seeing the error.

The only way we could support this is to create a new component inside the local component scope which means it'd get recreated over and over on render, which is pretty bad for performance.