change a css variable value on button click in react in javascript

To change a CSS variable value on button click in React using JavaScript, you can follow these steps:

  1. Define your CSS variable in your CSS file or inside a style tag in your component. Let's assume you have a CSS file called styles.css:

    :root {
      --primary-color: blue;
    }
    
    35 chars
    4 lines
  2. Import the CSS file or style in your React component:

    import React from 'react';
    import './styles.css';
    
    function App() {
      // ...
    }
    
    79 chars
    7 lines
  3. Create a state variable in your React component to store the value of the CSS variable:

    import React, { useState } from 'react';
    
    function App() {
      const [primaryColor, setPrimaryColor] = useState("blue");
    
      // ...
    }
    
    131 chars
    8 lines
  4. Assign the value of the CSS variable to the state variable:

    import React, { useState } from 'react';
    
    function App() {
      const [primaryColor, setPrimaryColor] = useState("blue");
    
      const handleClick = () => {
        setPrimaryColor("red");
      };
    
      return (
        <div>
          <button onClick={handleClick}>Change Color</button>
          {/* Use the primaryColor state variable in your CSS */}
          <h1 style={{ color: primaryColor }}>Hello World</h1>
        </div>
      );
    }
    
    402 chars
    18 lines
  5. Whenever the button is clicked, call the handleClick function to update the state variable (primaryColor) to the desired value (e.g., "red" in this example).

  6. Use the updated state variable in your CSS to dynamically change the value of the CSS variable (e.g., set the text color to the primaryColor state variable in the h1 element's style prop).

Now, when the button is clicked, the CSS variable value will be updated, and the text color will change accordingly.

Remember to replace "blue" and "red" with actual values you want to use.

Note: If you want to change multiple CSS variables at once, you can create separate state variables for each and update them accordingly.

related categories

gistlibby LogSnag