React - styling

React

Styling

Class binding

  • JSX: className attribute on a DOM element
    • Why? Because class is a reserved keyword
// Bind the class name to a fixed string
function Menu() {
  return <span className="menu navigation-menu">Menu</span>;
}
// Bind the class name based on a variable (prop, state ...)
function Menu({ isActive }: { isActive: boolean }) {
  let className = 'menu';
  if (this.props.isActive) {
    className += ' menu-active';
  }
  return <span className={className}>Menu</span>
}

Class binding

  • JSX: className attribute on a DOM element
import cn from 'classnames';

function Row(
  { isSelected, size }:
  { isSelected: boolean, size: string }
) {
  return (
    <div className={cn('row', {
      selected: isSelected,
      large: size === 'large',
      small: size === 'small',
    })}>
      ...
    </div>
  );
}

Style binding

  • JSX: style attribute on a DOM element
    • Can be useful
    • But... avoid too much inline styles (readability)
// Bind the text color to a fixed color
function Menu() {
  return <span style={{ color: "red" }}>Menu</span>;
}
// Bind the text color based on a variable (prop, state ...)
function Menu({ isValid }: { isValid: boolean }) {
  return <span style={{ color: isValid ? "green" : "red" }}>Menu</span>
}

CSS Modules

  • Style collision: when multiple style rules are inadvertently applied to the same element(s)
    • e.g. in App.css : color → red
                 Menu.css : color → blue
    • Prevent with CSS Modules
      • ​👎 classes only
      • 👍 no style collision, improved IntelliSense

CSS Modules

  • With CSS Modules, remember:
    • Filename: component-name.module.css
    • Apply lowerCamelCase for class names
    • Use classes for local (component) styles
    • Put global selectors in index.css

Other options

Styling

  • CSS Modules and Tailwind:
    • Prevent style collision
    • Avoid unused or duplicate CSS
    • Offer better code completion
      VS Code extension (CSS Modules)
      VS Code extension (Tailwind CSS IntelliSense)

Conclusion

  • You can apply styling however you want, but:
    • Avoid inline styles, especially when complex
    • Only use global styles in index.css
    • Make sure there is no style collision
    • Be prepared to explain your approach

PGM3 - React: styling

By kareldesmet

PGM3 - React: styling

  • 10