iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌊

Why not try CSS variables instead of props for styling?

に公開

Contents

Many people tend to pass CSS in the following way:

Component.tsx
import React from 'react'
export const ParentComponent = () => {
  const btnStyles = {
    color: 'aquagreen',
    border: '1px solid aquagreen',
    backgroundColor: 'white',
    fontSize: '12px'
  }
  return (
    <div>
      <Button styles={btnStyles} text={"Hello Word"}/>
    </div>
  )
}
export const Button = ({ styles, text }) =>
       <Button styles={styles}>{text}</Button>

When using CSS variables:

ParentComponent.tsx
import React from 'react'
import Button from './Button'
import styled from 'styled-components'

const Root = styled.div`
  --primary-color: aquagreen;
  --bg-color: #eee;
  --btn-font-size: 18px;
  /* .... */
`
export const Parent = () =>
const onClick = () => ...
  <Root>
    <Button onClick={onClick}>Buy now</Button>
  </Root>

Button.tsx
const StyledButton = styled.button`
  background-color: var(--bg-color);
  font-size: var(--btn-font-size);
  color: var(--primary-color);
  /* Other styles */
`;

const Button = ({ children, onClick }) => (
  <StyledButton onClick={onClick}>
    {children}
  </StyledButton>
);

export default Button;

Points I thought were good

  • Styling can be separated from the JSX definition.
    • Reduces the number of lines.
  • CSS value processing is offloaded to the browser.
    • Reduces JavaScript processing.
    • Improves performance.

References

It discusses CSS variables and their impact on application performance, so please check it out as well 👍
https://epicreact.dev/css-variables/

Discussion