Home > Mobile >  What does it means () => css``; in React
What does it means () => css``; in React

Time:10-13

Hello I'm reading spectrum repo, for learning how they organize their React code, and specifically about styled-components.

In this file globals/index.js there is this bit of code, I understand what it does, but no why.

export const Truncate = () => css`
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  min-width: 0;
`;

It does the truncate trick, but how it gets used in a component the Truncate component, how is reused in an actual component.

What it means css``, is styled-components syntax?;

CodePudding user response:

This syntax is a way of calling functions in JS, check this out

console.log("hello world".split` `)

On their home page you have this example:

const Button = styled.a`
  /* This renders the buttons above... Edit me! */
  display: inline-block;
  border-radius: 3px;
  padding: 0.5rem 0;
  margin: 0.5rem 1rem;
  width: 11rem;
  background: transparent;
  color: white;
  border: 2px solid white;

  /* The GitHub button is a primary button
   * edit this to target it specifically! */
  ${props => props.primary && css`
    background: white;
    color: black;
  `}
`

This is just a way of calling the css function and passing arguments to it

CodePudding user response:

The short answer is there's nothing special about styled-components.

the func`` is a feature of javascript called tagged template literals

The use of what the css function returns is however a convention of style-components

CodePudding user response:

The first paragraph of the styled-components documentation tells us:

Utilising tagged template literals (a recent addition to JavaScript) and the power of CSS, styled-components allows you to write actual CSS code to style your components.

And here's the section for Tagged Templates on the MDN Template String documentation page.

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

So css here is a function that accepts a template string for processing.

CodePudding user response:

It's a function that returns css in the form of a template literal. This is not exclusive to styled components like the others are saying. There are plenty of css packages that use the css prop like emotion. It's just a way of passing css in JS to a component.

    const myFuntionalComponent = () => {
      const someCss = () => css`
        color: red;
      `;
      return (
        <div css={someCss()}/>
      )
    }
  • Related