codemotionapps/react-native-dark-mode

Support for class components

Closed this issue ยท 6 comments

Is there a way to make this also work with class components? Maybe a workaround?

You can play around with DarkModeContext. Just make sure to wrap your application in a DarkModeProvider with no props to avoid getting a value of current.
https://reactjs.org/docs/context.html

Thanks!

Could you please elaborate a little more on the DarkModeContext usage? I wrapped my application inside a DarkModeProvider but I have no idea on how to retrieve the system current theme inside a stateful component. ๐Ÿ˜ž

Any help will be very appreciated.

I am seconding teofilosalgado 's request to elaborate a little more on what "play around with DarkModeContent" is supposed to mean. It is extremely frustrating the way Hooks has completely alienated React developers. Those that have chosen to embrace it and pretend Class components never existed are not contributing to the community as much as they think they are.

I think I can put some help with example code for class-based components.

  1. Setup context provider for the app.
// App.js or top of the hierarchy in your app
import React, {Component} from 'react';
import {DarkModeProvider} from 'react-native-dark-mode';

export default class App extends Component {
  render() {
    return (
      <DarkModeProvider>
        <YourApp />
      </DarkModeProvider>
    );
  }
}
  1. Use the context with contextType or context consumer.
// class based component with contextType
import React, {Component} from 'react';
import {Text} from 'react-native';
import {DarkModeContext} from 'react-native-dark-mode';

export default class HelloWorldText extends Component {
  static contextType = DarkModeContext;
  render() {
    const isDarkMode = this.context === 'dark';
    return (
      <Text style={{color: isDarkMode ? '#ffffff' : '#000000'}}>
        {this.props.children}
      </Text>
    );
  }
}
// class based component with context consumer
import React, {Component} from 'react';
import {Text} from 'react-native';
import {DarkModeContext} from 'react-native-dark-mode';

export default class HelloWorldText extends Component {
  render() {
    return (
      <DarkModeContext.Consumer>
        {mode => (
          <Text style={{color: mode === 'dark' ? '#ffffff' : '#000000'}}>
            {this.props.children}
          </Text>
        )}
      </DarkModeContext.Consumer>
    );
  }
}

If you want to know about the context, you can find more detail in context page. It is really useful feature for both, class and function components.

Our programme was ending, And we need add dark mode now , But i can not get initalMode value dynamic... What's going on and How can i do?