Files
react-native/RNTester/js/examples/Dimensions/DimensionsExample.js
T
Spencer Ahrens 5ec382d1be New useWindowDimensions hook to replace most Dimensions usage
Summary:
Automatically provides and subscribes to dimension updates - super easy usage:
```
function MyComponent(props: Props) {
  const {width, height, scale, fontScale} = useWindowDimensions();
  return <Text ...
};
```

Only window for now - it's what people want 99% of the time, so we'll just shovel out a pit of success for them...

There are still cases where `Dimensions` is needed outside of React component render functions, like in GraphQL variables, so we need to keep the existing module.

Reviewed By: zackargyle

Differential Revision: D16525189

fbshipit-source-id: 0a049fb3be8d92888a8a69e3898d337b93422a09
2019-07-29 11:09:44 -07:00

69 lines
1.5 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its 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
*/
'use strict';
import * as React from 'react';
import {Dimensions, Text, useWindowDimensions} from 'react-native';
class DimensionsSubscription extends React.Component<
{dim: string},
{dims: Object},
> {
state = {
dims: Dimensions.get(this.props.dim),
};
componentDidMount() {
Dimensions.addEventListener('change', this._handleDimensionsChange);
}
componentWillUnmount() {
Dimensions.removeEventListener('change', this._handleDimensionsChange);
}
_handleDimensionsChange = dimensions => {
this.setState({
dims: dimensions[this.props.dim],
});
};
render() {
return <Text>{JSON.stringify(this.state.dims, null, 2)}</Text>;
}
}
exports.title = 'Dimensions';
exports.description = 'Dimensions of the viewport';
exports.examples = [
{
title: 'useWindowDimensions hook',
render() {
const DimensionsViaHook = () => {
const dims = useWindowDimensions();
return <Text>{JSON.stringify(dims, null, 2)}</Text>;
};
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" />;
},
},
];