[How to] use CSS Variables in React Component

devneagu

devneagu

Posted on December 9, 2022

[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.

💖 💪 🙅 🚩
devneagu
devneagu

Posted on December 9, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related