Files
react-native/packages/rn-tester/js/examples/Dimensions/DimensionsExample.js
T
Marco Fiorito 745e26288c refactor(rn tester app): change dimensions example to hooks (#35084)
Summary:
This pull request migrates the dimensions example to using React Hooks.

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

Pull Request resolved: https://github.com/facebook/react-native/pull/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
2022-10-31 16:23:54 -07:00

60 lines
1.5 KiB
JavaScript

/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import {Dimensions, Text, useWindowDimensions} from 'react-native';
import * as React from 'react';
import {useState, useEffect} from 'react';
type Props = {dim: string};
function DimensionsSubscription(props: Props) {
const [dims, setDims] = useState(() => Dimensions.get(props.dim));
useEffect(() => {
const subscription = Dimensions.addEventListener('change', dimensions => {
setDims(dimensions[props.dim]);
});
return () => subscription.remove();
}, [props.dim]);
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
}
const DimensionsViaHook = () => {
const dims = useWindowDimensions();
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
};
exports.title = 'Dimensions';
exports.category = 'UI';
exports.documentationURL = 'https://reactnative.dev/docs/dimensions';
exports.description = 'Dimensions of the viewport';
exports.examples = [
{
title: 'useWindowDimensions hook',
render(): React.Node {
return <DimensionsViaHook />;
},
},
{
title: 'Non-component `get` API: window',
render(): React.Element<any> {
return <DimensionsSubscription dim="window" />;
},
},
{
title: 'Non-component `get` API: screen',
render(): React.Element<any> {
return <DimensionsSubscription dim="screen" />;
},
},
];