React styled-components theme-provider dynamic theme

3.1k views Asked by At

I'm trying to achieve dark and light themes in my React app. I know how themes work, so I'm configuring my button like below, for example :

const Button = styled.button`
   /* some styles */
    color: ${props => props.theme.main}
`;

Then I'm defining themes as consts:

const dark = {
    main: 'black',
    text: 'switch to light mode'
};

const light = {
    main: 'white',
    text: 'switch to dark mode'
};

And when I want to use the theme somewhere I do it like this:

  <ThemeProvider theme={dark}>
    <Button>{dark.text}</Button>
  </ThemeProvider>

But what I want to achieve is to change the theme dynamically (on a click function on the button probably). I'm kind of new to React so please don't be mean to me.

1

There are 1 answers

2
Marcin Pietruszka On BEST ANSWER

Something like this? Demo

import React, { Component } from 'react';
import { render } from 'react-dom';
import styled, { ThemeProvider } from 'styled-components';

const themes = {
  'light': {
    main: '#EFEFEF',
  },
  'dark': {
    main: '#666',
  }
}

const DynamicDiv = styled.div`
  background: ${({ theme }) => theme.main};
`

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      theme: themes['light']
    };
  }

  handleDark = () => {
    this.setState({ theme: themes['dark'] })
  }

  render() {
    return (
      <ThemeProvider theme={this.state.theme}>
        <div>
          <DynamicDiv>{this.state.name}</DynamicDiv>
          <div onClick={this.handleDark}>Change to Dark</div>
        </div>
      </ThemeProvider>
    );
  }
}

render(<App />, document.getElementById('root'));