DEV Community

devneagu
devneagu

Posted on

10

[How to] use CSS Variables in React Component

To use CSS variables (also known as "custom properties") in React components, you can define the variables in a separate CSS file, and then use the style attribute in your React components to reference and apply the variables.

Here is an example of how you can use CSS variables in a React component:

First, define the variables in a separate CSS file, such as styles.css:

:root {
  --primary-color: #f1f1f1;
  --secondary-color: #d1d1d1;
}
Enter fullscreen mode Exit fullscreen mode

Then, in your React component, import the CSS file and use the style attribute to reference and apply the variables:

import './styles.css';

function MyComponent() {
  return (
    <div style={{
      backgroundColor: 'var(--primary-color)',
      color: 'var(--secondary-color)'
    }}>
      This is my component
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the CSS variables are defined in the :root selector, which means that they are available to all elements on the page. The style attribute in the React component is used to reference and apply the variables to the div element, using the var() function.

By using CSS variables in this way, you can easily reuse and manage the styles in your React components, and make it easier to maintain and update your CSS styles.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay