Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
How to change css when theme changes in React?

I am developing a library of react components and asked an important question. How to correctly change styles (css) when changing the application theme.
Appeal to those who already have experience in this and who can advise their approach or solution.
Now I'll tell you how it works for me:

I have my own themeProvider wrapped in a Context with the ability to change the theme. When the theme changes in the provider, the changeCssVariables method is called.

export const changeCssVariables = (theme) => {
    const root = document.querySelector(':root');

    // root.style.setProperty('--default-color', 'orange');

    const cssVariables = [
        'color', 
        'background',

        'color-uibutton',
        'background-uibutton',
        'box-shadow-uibutton',
        'color-disabled-uibutton',
        'background-disabled-uibutton',

        'background-uiradiobutton',

        'color-uiinputext',
        'color-notes-uiinputext',

        'color-subsection',
        'background-subsection',
        'box-shadow-subsection',
        'alt-subsection',
        'on-subsection',
        'off-subsection',

        
    ];

    cssVariables.forEach(element => {
        root.style.setProperty(
            `--default-${element}`, 
            `var(--theme-${theme}-${element})`
        );
    })
}

What happens in general: it has a global CSS with variables default, light and dark themes. When changing the theme, a method is called that changes the default variable to the variable of the selected theme.
Example css:

--default-color: var(--theme-light-color);
/* Themes */

    --theme-light-color: #000;
    --theme-dark-color: #fff;

I don't like that you have to pull in all the css and change it this way. What is the solution? Thanks for the help!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Found a solution in using styled-components package
Created my wrapper as ThemeProvider (Context)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!