Styled components

Styled components in Stratox allow you to add custom CSS styles directly to your components. These styles are dynamically loaded and unloaded with the component, minimizing the risk of CSS collisions and improving performance.

Example Usage

You can utilize the context argument in your component to manage styles. The context represents the component's instance and provides access to methods like addStyles.

export default function MyComponent(props, container, helper, context) {
  // Add styles to the component
  context.addStyles({
    '.headline-1': {
      fontSize: '3rem',
    },
    '.custom-button': {
      color: '#FFF',
      fontSize: '1.5rem',
      backgroundColor: 'purple',
      padding: '1rem 2rem',
    },
  });

  return `
    <article class="relative card-1 border-bottom ingress">
      <div class="wrapper md">
        <h1 class="headline-1">${props.title}</h1>
        <p>${props.description}</p>
        <a class="custom-button" href="#about">Visit page</a>
      </div>
    </article>
  `;
}

In this example:

  • The .headline-1 class gets a custom font size.

  • The .custom-button class gets styled with unique colors, font size, and padding.

Binding Styles to Components

By default, styles added with addStyles are scoped to the component they are defined in. If you call addStyles multiple times for the same component, the styles will be overwritten.

To define multiple style blocks within the same component, you can assign a unique identifier to the styles:

// 1. Styles bound to the component
context.addStyles({
  '.headline-1': {
    fontSize: '3rem',
  },
  '.custom-button': {
    color: '#FFF',
    fontSize: '1.5rem',
    backgroundColor: 'purple',
    padding: '1rem 2rem',
  },
});

// 2. Additional styles bound to the component with a unique identifier
context.addStyles({
  'p': {
    fontSize: '1.8rem',
  },
}, 'moreStyles');

Clearing Styles

You can dynamically clear styles during a component's lifecycle. This is particularly useful for temporary components like modals or popups.

// Clear all styles bound to the component
context.clearStyles();

// Clear styles associated with a specific identifier
context.clearStyles('moreStyles');

Why Use Styled Components?

Styled components offer a great way to add complementary styles to your components without bloating your global CSS. They work harmoniously with popular CSS libraries like Tailwind CSS, Bootstrap, or Sass.

Key benefits:

  • Dynamic Loading: Styles are loaded only when the component is active.

  • Scoped Styles: Avoid CSS conflicts and ensure styles are isolated.

  • Performance: Unused styles are unloaded automatically.

With Stratox styled components, you get the flexibility of CSS-in-JS while maintaining simplicity and performance in your applications.

Last updated