Skip to content

Commit

Permalink
refactor(rn tester app): change dimensions example to hooks (#35084)
Browse files Browse the repository at this point in the history
Summary:
This pull request migrates the dimensions example to using React Hooks.

## Changelog
[General] [Changed] - RNTester: Migrate Dimensions to hooks

Pull Request resolved: #35084

Test Plan: The animation works exactly as it did as when it was a class component

Reviewed By: yungsters

Differential Revision: D40779014

Pulled By: NickGerleman

fbshipit-source-id: e740684d3022a945da5abc33b2e8834c6cfabb97
  • Loading branch information
Marcoo09 authored and facebook-github-bot committed Oct 31, 2022
1 parent 07bd590 commit 745e262
Showing 1 changed file with 11 additions and 25 deletions.
36 changes: 11 additions & 25 deletions packages/rn-tester/js/examples/Dimensions/DimensionsExample.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,38 +8,24 @@
* @flow
*/

import type {EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter';
import {Dimensions, Text, useWindowDimensions} from 'react-native';
import * as React from 'react';
import {useState, useEffect} from 'react';

class DimensionsSubscription extends React.Component<
{dim: string, ...},
{dims: Object, ...},
> {
state: {dims: any, ...} = {
dims: Dimensions.get(this.props.dim),
};
type Props = {dim: string};

_dimensionsSubscription: ?EventSubscription;
function DimensionsSubscription(props: Props) {
const [dims, setDims] = useState(() => Dimensions.get(props.dim));

componentDidMount() {
this._dimensionsSubscription = Dimensions.addEventListener(
'change',
dimensions => {
this.setState({
dims: dimensions[this.props.dim],
});
},
);
}
useEffect(() => {
const subscription = Dimensions.addEventListener('change', dimensions => {
setDims(dimensions[props.dim]);
});

componentWillUnmount() {
this._dimensionsSubscription?.remove();
}
return () => subscription.remove();
}, [props.dim]);

render(): React.Node {
return <Text>{JSON.stringify(this.state.dims, null, 2)}</Text>;
}
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
}

const DimensionsViaHook = () => {
Expand Down

0 comments on commit 745e262

Please sign in to comment.