Home > AI > Frontend > ReactJS >

styled-components.macro

This package supports to write raw CSS in your React code

Step 1: install

npm i styled-components
npm i styled-components.macro

Step 2: This example code shows the the usage of this package and transition-delay effect

import React, {useState, useRef} from 'react';
import "styled-components/macro";


const fruits = [
  'Apple',      //   0ms = 100ms * 0
  'Banana',     // 100ms = 100ms * 1
  'Cherry',     // 200ms = 100ms * 2
  'Grape',      // 300ms = 100ms * 3
  'Kiwi',       // 400ms = 100ms * 4
  'Lemon',      // 500ms = 100ms * 5
  'Pear',       // 600ms = 100ms * 6
  'Pineapple',  // 700ms = 100ms * 7
];
const stagger = 100;

class Item extends React.Component {
  render() {
    return (
      <div css={`
      transform: ${this.props.isVisible
        ? 'translateX(0%)'
        : 'translateX(100%)'};
      transition: transform 0.5s ease-in-out;
      transition-delay: ${stagger * this.props.index}ms;
      `}>
        {this.props.name}
      </div>
    );
  }
};

class App extends React.Component {
  state = {
    isVisible: true
  }

  render() {
    return (
      <div css={`
        width: 300px; // "styled-components/macro" enables raw CSS!
        background-color: red;
      `}>

        <button onClick={() => this.setState({isVisible: !this.state.isVisible})}>
          TOGGLE
        </button>

        {fruits.map((fruit, index) => {
          return (
            <Item 
              isVisible={this.state.isVisible}
              index={index}
              name={fruit}
            />
          )
        })}

      </div>
    );
  }
};

export default App;

Leave a Reply