Uladzislau Radzko
Uladzislau Radzko

Reputation: 123

Theming in React with Redux and ThemeProvider

There is only one theme in my app.

ReactDOM.render(
    <Provider store={store}>
        <ThemeProvider theme={theme}>
            <App />
        </ThemeProvider>
    </Provider>,
    root,
);

I want to have some themes and the possibility to change them dynamically. When I tried putting my theme into the window object and change it during the app, I see that my styles didn't change. I mean, I had the following code

<ThemeProvider theme={window.theme}>
    <App />
</ThemeProvider>

And when I chage window.theme in different files like

Object.assign(window.theme, newTheme)

My component file with styles like Component.style.js (with jss) didn't re-render. And I had new theme in my app, but the components had old styles.

Should I store my theme in my store? Is it a good way to have the possibility to change a theme in any part of my application? Could you tell me how to organize theming correctly? Thanks in advance!

Upvotes: 1

Views: 3777

Answers (1)

ZakDaniels99
ZakDaniels99

Reputation: 505

Based on your comments, I see that you're not using a UI component library but React Context API to provide a theme, and Redux to manage your application state.

Should I store my theme in my store?

Yes. Since you're already using Redux to handle application state, there's no need to mix in React's Context API as well. You're solving the same problem twice otherwise, and your code's just going to be more difficult to maintain. Rather make an object representing your UI in your Redux store.

Is it a good way to have the possibility to change a theme in any part of my application?

I wouldn't worry too much about this. Whether you use Redux or React's Context API, both provide you with a mechanism of reading and updating global application state from anywhere within your application. You can decide later on whether you want the portion of your global application state that handles UI to have change handlers; whether it be through Redux reducers or Context API's consumers.

Could you tell me how to organize theming correctly?

Take a look at how Material UI does it. There's no better guide than a framework that's being used quite extensively.

Back to your initial question, "Why doesn't my app theme update?". Since your using React's Context API, you need to use a consumer component to update your provider's value. Your context provider will notify child components of the change and they'll rerender. This logic doesn't run if you use an object assign.

Upvotes: 2

Related Questions