From 22576fa615f0308aab00686235295b3dc0d34852 Mon Sep 17 00:00:00 2001 From: Marco Fiorito Date: Mon, 28 Nov 2022 04:42:51 -0800 Subject: [PATCH] refactor(rn tester app): change appearence example to hooks (#35114) Summary: This pull request migrates the appearance example to using React Hooks. ## Changelog [General] [Changed] - RNTester: Migrate Appearence to hooks Pull Request resolved: https://github.com/facebook/react-native/pull/35114 Test Plan: The animation works exactly as it did as when it was a class component Reviewed By: cortinico Differential Revision: D41531005 Pulled By: cipolleschi fbshipit-source-id: a864766a3bb58a7f0c2b9c4ed8f731ee84713b26 --- .../examples/Appearance/AppearanceExample.js | 53 ++++++++----------- 1 file changed, 21 insertions(+), 32 deletions(-) diff --git a/packages/rn-tester/js/examples/Appearance/AppearanceExample.js b/packages/rn-tester/js/examples/Appearance/AppearanceExample.js index 9272c6ab6c0..e330ae2954b 100644 --- a/packages/rn-tester/js/examples/Appearance/AppearanceExample.js +++ b/packages/rn-tester/js/examples/Appearance/AppearanceExample.js @@ -9,47 +9,36 @@ */ import * as React from 'react'; +import {useState, useEffect} from 'react'; import {Appearance, Text, useColorScheme, View} from 'react-native'; import type {AppearancePreferences} from 'react-native/Libraries/Utilities/NativeAppearance'; -import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; import {RNTesterThemeContext, themes} from '../../components/RNTesterTheme'; -class ColorSchemeSubscription extends React.Component< - {...}, - {colorScheme: ?string, ...}, -> { - _subscription: ?EventSubscription; +function ColorSchemeSubscription() { + const [colorScheme, setScheme] = useState(Appearance.getColorScheme()); - state: {colorScheme: ?string, ...} = { - colorScheme: Appearance.getColorScheme(), - }; - - componentDidMount() { - this._subscription = Appearance.addChangeListener( + useEffect(() => { + const subscription = Appearance.addChangeListener( (preferences: AppearancePreferences) => { - const {colorScheme} = preferences; - this.setState({colorScheme}); + const {colorScheme: scheme} = preferences; + setScheme(scheme); }, ); - } - componentWillUnmount() { - this._subscription?.remove(); - } + return () => subscription?.remove(); + }, [setScheme]); - render(): React.Node { - return ( - - {theme => { - return ( - - {this.state.colorScheme} - - ); - }} - - ); - } + return ( + + {theme => { + return ( + + {colorScheme} + + ); + }} + + ); } const ThemedContainer = (props: {children: React.Node}) => ( @@ -69,7 +58,7 @@ const ThemedContainer = (props: {children: React.Node}) => ( ); -const ThemedText = (props: {children: React.Node}) => ( +const ThemedText = (props: {children: React.Node | string}) => ( {theme => { return {props.children};