Alex Turbin
Alex Turbin

Reputation: 2702

useTheme equivalent for class component

I would like to use the current theme in my class component.

According to the latest (RN 5.x) documentation, there is a useTheme() hook for that purposes. However, it doesn't mention any class equivalent.

I found ThemeContext.Consumer in RN 4.x but it is not available in 5.x anymore.

Is it possible to achieve the effect of useTheme() in some other way for a class component?

Upvotes: 1

Views: 2135

Answers (1)

CevaComic
CevaComic

Reputation: 2104

This is not so elegant, but it will do the job for you.

Here is my method to access the theme inside a class component:

import React from 'react'
import { SafeAreaView, Text } from 'react-native'
import { useTheme } from '@react-navigation/native'

export default class Home extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            theme: undefined
        }
    }

    setTheme = theme => {
        this.setState({theme})
    }

    render () {

        console.log('theme', this.state.theme)

        return (
            <SafeAreaView>
                <SetTheme setTheme={this.setTheme} />
                <Text>Hello world</Text>
            </SafeAreaView>
        )
    }

}

const SetTheme = ({ setTheme }) => {
    const theme = useTheme()

    React.useEffect(() => {
        setTheme(theme)
        return () => null
    },[])

    return null
}

Upvotes: 2

Related Questions