Search code examples
cssreactjssassstyled-components

Can styled components handle computations like SCSS?


With SCSS, I can create CSS magic like so:

@for $i from 1 through $total-items {
  li:nth-child(#{$i}) {
    animation-delay: .25s * $i;
  }
}

I'm now working on a React App that uses styled components. Does styled components allow for the above somehow?


Solution

  • You can cut out the middleman and do the calculation during the render or you can pass an index to something that returns an object that will generate your style.

    totalItems.map((item, index) => {
       <li style={animationDelay: `${.25 * index}s`}>{item.name}</li>
    })
    

    otherwise you can create a style and pass in the index to create the style object

    const style = (index) => {
      return {
        animationDelay: `${.25 * index}s`
      }
    }
    

    But if you're looking for the styled component way pass your component here with an attr of index={the index of the item}

    const StyledLink = styled(component here)`
        animationDelay: ${props => props.index};
    `;