Fix RNTester strict mode warnings (#48619)

Summary:
While investigating https://github.com/facebook/react-native/issues/22186, some false positives showed up as some of the examples also have non-strict mode compatible code.

In this PR:

- Converting from class to functional components some TextInput and Image examples that were using `UNSAFE_` lifecycles.
- Unifying the auto-expanding example as it was exactly the same for iOS and Android.

## Changelog:

[INTERNAL] - Fix RNTester strict mode warnings for TextInput and Image examples

Pull Request resolved: https://github.com/facebook/react-native/pull/48619

Test Plan:
- Wrapped the the entry app component in `RNTesterAppShared.js` with `StrictMode` and verified that no warnings are shown anymore for the updated components.
- Checked the examples are still working as they were.

Reviewed By: fabriziocucci

Differential Revision: D68094402

Pulled By: rshest

fbshipit-source-id: e13878cb290735095afaef3d0377fd6dab33c380
This commit is contained in:
Mateo Guzmán authored and Facebook GitHub Bot committed 2025-01-13 05:11:13 -08:00
1 parent 6cb2684b43
commit d4407d6f77
5 files changed
+191 -382

No files matched your search

@@ -35,37 +35,28 @@ type ImageSource = $ReadOnly<{|
uri: string,
|}>;
type BlobImageState = {|
objectURL: ?string,
|};
type BlobImageProps = $ReadOnly<{|
url: string,
|}>;
class BlobImage extends React.Component<BlobImageProps, BlobImageState> {
state: BlobImageState = {
objectURL: null,
};
const BlobImage = ({url}: BlobImageProps): React.Node => {
const [objectURL, setObjectURL] = React.useState<?string>(null);
UNSAFE_componentWillMount() {
React.useEffect(() => {
// $FlowFixMe[unused-promise]
(async () => {
const result = await fetch(this.props.url);
const result = await fetch(url);
const blob = await result.blob();
const objectURL = URL.createObjectURL(blob);
this.setState({objectURL});
setObjectURL(URL.createObjectURL(blob));
})();
}
}, [url]);
render(): React.Node {
return this.state.objectURL !== null ? (
<Image source={{uri: this.state.objectURL}} style={styles.base} />
) : (
<Text>Object URL not created yet</Text>
);
}
}
return objectURL !== null ? (
<Image source={{uri: objectURL}} style={styles.base} />
) : (
<Text>Object URL not created yet</Text>
);
};
type BlobImageExampleState = {||};
@@ -88,146 +79,121 @@ class BlobImageExample extends React.Component<
}
}
type NetworkImageCallbackExampleState = {|
events: Array<string>,
startLoadPrefetched: boolean,
mountTime: number,
imageHash: number,
|};
type NetworkImageCallbackExampleProps = $ReadOnly<{|
source: ImageSource,
prefetchedSource: ImageSource,
|}>;
class NetworkImageCallbackExample extends React.Component<
NetworkImageCallbackExampleProps,
NetworkImageCallbackExampleState,
> {
state: NetworkImageCallbackExampleState = {
events: [],
startLoadPrefetched: false,
mountTime: Date.now(),
imageHash: Date.now(),
const NetworkImageCallbackExample = ({
source,
prefetchedSource,
}: NetworkImageCallbackExampleProps): React.Node => {
const [events, setEvents] = React.useState<$ReadOnlyArray<string>>([]);
const [startLoadPrefetched, setStartLoadPrefetched] = React.useState(false);
const [mountTime, setMountTime] = React.useState(Date.now());
React.useEffect(() => {
setMountTime(Date.now());
}, []);
const _loadEventFired = (event: string) => {
setEvents(state => [...state, event]);
};
UNSAFE_componentWillMount() {
this.setState({mountTime: Date.now()});
}
_loadEventFired = (event: string) => {
this.setState(state => ({
events: [...state.events, event],
}));
};
updateLoadingImageHash = () => {
this.setState({imageHash: Date.now()});
};
render(): React.Node {
const {mountTime} = this.state;
return (
<View>
<Image
source={this.props.source}
style={[styles.base, styles.visibleOverflow]}
onError={event => {
this._loadEventFired(
`✘ onError "${event.nativeEvent.error}" (+${Date.now() - mountTime}ms)`,
return (
<View>
<Image
source={source}
style={[styles.base, styles.visibleOverflow]}
onError={event => {
_loadEventFired(
`✘ onError "${event.nativeEvent.error}" (+${Date.now() - mountTime}ms)`,
);
}}
onLoadStart={() =>
_loadEventFired(`✔ onLoadStart (+${Date.now() - mountTime}ms)`)
}
onProgress={event => {
const {loaded, total} = event.nativeEvent;
const percent = Math.round((loaded / total) * 100);
_loadEventFired(
`✔ onProgress ${percent}% (+${Date.now() - mountTime}ms)`,
);
}}
onLoad={event => {
if (event.nativeEvent.source) {
const url = event.nativeEvent.source.uri;
_loadEventFired(
`✔ onLoad (+${Date.now() - mountTime}ms) for URL ${url}`,
);
}}
} else {
_loadEventFired(`✔ onLoad (+${Date.now() - mountTime}ms)`);
}
}}
onLoadEnd={() => {
_loadEventFired(`✔ onLoadEnd (+${Date.now() - mountTime}ms)`);
setStartLoadPrefetched(true);
prefetchTask.then(
() => {
_loadEventFired(`✔ prefetch OK (+${Date.now() - mountTime}ms)`);
// $FlowFixMe[unused-promise]
Image.queryCache([IMAGE_PREFETCH_URL]).then(map => {
const result = map[IMAGE_PREFETCH_URL];
if (result) {
_loadEventFired(
`✔ queryCache "${result}" (+${Date.now() - mountTime}ms)`,
);
} else {
_loadEventFired(
`✘ queryCache (+${Date.now() - mountTime}ms)`,
);
}
});
},
error => {
_loadEventFired(
`✘ prefetch failed (+${Date.now() - mountTime}ms)`,
);
},
);
}}
/>
{startLoadPrefetched && (
<Image
source={prefetchedSource}
style={[styles.base, styles.visibleOverflow]}
onLoadStart={() =>
this._loadEventFired(`✔ onLoadStart (+${Date.now() - mountTime}ms)`)
_loadEventFired(
`✔ (prefetched) onLoadStart (+${Date.now() - mountTime}ms)`,
)
}
onProgress={event => {
const {loaded, total} = event.nativeEvent;
const percent = Math.round((loaded / total) * 100);
this._loadEventFired(
`✔ onProgress ${percent}% (+${Date.now() - mountTime}ms)`,
);
}}
onLoad={event => {
if (event.nativeEvent.source) {
const url = event.nativeEvent.source.uri;
this._loadEventFired(
`✔ onLoad (+${Date.now() - mountTime}ms) for URL ${url}`,
_loadEventFired(
`✔ (prefetched) onLoad (+${
Date.now() - mountTime
}ms) for URL ${url}`,
);
} else {
this._loadEventFired(`✔ onLoad (+${Date.now() - mountTime}ms)`);
}
}}
onLoadEnd={() => {
this._loadEventFired(`✔ onLoadEnd (+${Date.now() - mountTime}ms)`);
this.setState({startLoadPrefetched: true}, () => {
prefetchTask.then(
() => {
this._loadEventFired(
`✔ prefetch OK (+${Date.now() - mountTime}ms)`,
);
// $FlowFixMe[unused-promise]
Image.queryCache([IMAGE_PREFETCH_URL]).then(map => {
const result = map[IMAGE_PREFETCH_URL];
if (result) {
this._loadEventFired(
`✔ queryCache "${result}" (+${
Date.now() - mountTime
}ms)`,
);
} else {
this._loadEventFired(
`✘ queryCache (+${Date.now() - mountTime}ms)`,
);
}
});
},
error => {
this._loadEventFired(
`✘ prefetch failed (+${Date.now() - mountTime}ms)`,
);
},
_loadEventFired(
`✔ (prefetched) onLoad (+${Date.now() - mountTime}ms)`,
);
});
}
}}
onLoadEnd={() =>
_loadEventFired(
`✔ (prefetched) onLoadEnd (+${Date.now() - mountTime}ms)`,
)
}
/>
{this.state.startLoadPrefetched ? (
<Image
source={this.props.prefetchedSource}
style={[styles.base, styles.visibleOverflow]}
onLoadStart={() =>
this._loadEventFired(
`✔ (prefetched) onLoadStart (+${Date.now() - mountTime}ms)`,
)
}
onLoad={event => {
// Currently this image source feature is only available on iOS.
if (event.nativeEvent.source) {
const url = event.nativeEvent.source.uri;
this._loadEventFired(
`✔ (prefetched) onLoad (+${
Date.now() - mountTime
}ms) for URL ${url}`,
);
} else {
this._loadEventFired(
`✔ (prefetched) onLoad (+${Date.now() - mountTime}ms)`,
);
}
}}
onLoadEnd={() =>
this._loadEventFired(
`✔ (prefetched) onLoadEnd (+${Date.now() - mountTime}ms)`,
)
}
/>
) : null}
<RNTesterText style={styles.networkImageText} variant="label">
{this.state.events.join('\n')}
</RNTesterText>
</View>
);
}
}
)}
<RNTesterText style={styles.networkImageText}>
{events.join('\n')}
</RNTesterText>
</View>
);
};
type NetworkImageExampleState = {|
error: ?string,
@@ -16,123 +16,20 @@ import type {
} from '../../types/RNTesterTypes';
import ExampleTextInput from './ExampleTextInput';
import TextInputSharedExamples from './TextInputSharedExamples';
import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
const TextInputSharedExamples = require('./TextInputSharedExamples.js');
const React = require('react');
const {StyleSheet, Switch, Text, View} = require('react-native');
const ToggleDefaultPaddingExample = (): React.Node => {
const [hasPadding, setHasPadding] = React.useState(false);
class ToggleDefaultPaddingExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
constructor(props) {
super(props);
this.state = {hasPadding: false};
}
render(): React.Node {
return (
<View>
<ExampleTextInput style={this.state.hasPadding ? {padding: 0} : null} />
<Text
onPress={() => this.setState({hasPadding: !this.state.hasPadding})}>
Toggle padding
</Text>
</View>
);
}
}
class AutogrowingTextInputExample extends React.Component<{...}> {
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
constructor(props) {
super(props);
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
* when making Flow check .android.js files. */
this.state = {
multiline: true,
fullWidth: true,
text: '',
contentSize: {
width: 0,
height: 0,
},
};
}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
UNSAFE_componentWillReceiveProps(props) {
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
* when making Flow check .android.js files. */
this.setState({
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
* when making Flow check .android.js files. */
multiline: props.multiline,
});
}
render(): React.Node {
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
* when making Flow check .android.js files. */
const {style, multiline, ...props} = this.props;
return (
<View>
<Text>Full width:</Text>
<Switch
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
value={this.state.fullWidth}
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
onValueChange={value => this.setState({fullWidth: value})}
/>
<Text>Multiline:</Text>
<Switch
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
value={this.state.multiline}
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
onValueChange={value => this.setState({multiline: value})}
/>
<Text>TextInput:</Text>
{/* $FlowFixMe(>=0.122.0 site=react_native_android_fb) This comment
* suppresses an error found when Flow v0.122.0 was deployed. To see
* the error, delete this comment and run Flow. */}
<ExampleTextInput
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
multiline={this.state.multiline}
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
style={[style, {width: this.state.fullWidth ? '100%' : '50%'}]}
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
onChangeText={value => this.setState({text: value})}
onContentSizeChange={event =>
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
this.setState({contentSize: event.nativeEvent.contentSize})
}
{...props}
/>
<Text>Plain text value representation:</Text>
{/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */}
<Text>{this.state.text}</Text>
{/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */}
<Text>Content Size: {JSON.stringify(this.state.contentSize)}</Text>
</View>
);
}
}
return (
<View>
<ExampleTextInput style={hasPadding ? {padding: 0} : null} />
<Text onPress={() => setHasPadding(!hasPadding)}>Toggle padding</Text>
</View>
);
};
const styles = StyleSheet.create({
multiline: {
@@ -408,30 +305,6 @@ const examples: Array<RNTesterModuleExample> = [
);
},
},
{
title: 'Auto-expanding',
render: function (): React.Node {
return (
<View style={styles.wrappedText}>
<AutogrowingTextInputExample
enablesReturnKeyAutomatically={true}
returnKeyType="done"
multiline={true}
style={{maxHeight: 400, minHeight: 20, backgroundColor: '#eeeeee'}}>
generic generic generic
<Text style={{fontSize: 6, color: 'red'}}>
small small small small small small
</Text>
<Text>regular regular</Text>
<Text style={{fontSize: 30, color: 'green'}}>
huge huge huge huge huge
</Text>
generic generic generic
</AutogrowingTextInputExample>
</View>
);
},
},
{
title: 'Text Auto Complete',
render: function (): React.Node {
@@ -18,10 +18,9 @@ import type {KeyboardType} from 'react-native/Libraries/Components/TextInput/Tex
import RNTesterText from '../../components/RNTesterText';
import ExampleTextInput from './ExampleTextInput';
const TextInputSharedExamples = require('./TextInputSharedExamples.js');
const React = require('react');
const {
import TextInputSharedExamples from './TextInputSharedExamples';
import React from 'react';
import {
Alert,
Button,
InputAccessoryView,
@@ -30,7 +29,7 @@ const {
Text,
TextInput,
View,
} = require('react-native');
} from 'react-native';
class WithLabel extends React.Component<$FlowFixMeProps> {
render(): React.Node {
@@ -210,67 +209,6 @@ class SecureEntryExample extends React.Component<$FlowFixMeProps, any> {
}
}
class AutogrowingTextInputExample extends React.Component<
$FlowFixMeProps,
$FlowFixMeState,
> {
constructor(props: any | void) {
super(props);
this.state = {
multiline: true,
fullWidth: true,
text: '',
contentSize: {
width: 0,
height: 0,
},
};
}
UNSAFE_componentWillReceiveProps(props: any) {
this.setState({
multiline: props.multiline,
});
}
render(): React.Node {
const {style, multiline, ...props} = this.props;
return (
<View>
<RNTesterText>Full width:</RNTesterText>
<Switch
value={this.state.fullWidth}
onValueChange={value => this.setState({fullWidth: value})}
/>
<RNTesterText>Multiline:</RNTesterText>
<Switch
value={this.state.multiline}
onValueChange={value => this.setState({multiline: value})}
/>
<RNTesterText>TextInput:</RNTesterText>
<ExampleTextInput
value="prop"
multiline={this.state.multiline}
style={[style, {width: this.state.fullWidth ? '100%' : '50%'}]}
onChangeText={value => this.setState({text: value})}
onContentSizeChange={event =>
this.setState({contentSize: event.nativeEvent.contentSize})
}
{...props}
/>
<RNTesterText>Plain text value representation:</RNTesterText>
<RNTesterText>{this.state.text}</RNTesterText>
<RNTesterText>
Content Size: {JSON.stringify(this.state.contentSize)}
</RNTesterText>
</View>
);
}
}
const TextInputWithFocusButton = () => {
const inputToFocusRef = React.useRef<React.ElementRef<
typeof TextInput,
@@ -809,37 +747,6 @@ const textInputExamples: Array<RNTesterModuleExample> = [
);
},
},
{
title: 'Auto-expanding',
render: function (): React.Node {
return (
<View>
<AutogrowingTextInputExample
enablesReturnKeyAutomatically={true}
returnKeyType="done"
multiline={true}
style={{
maxHeight: 400,
minHeight: 20,
paddingTop: 0,
backgroundColor: '#eeeeee',
color: 'blue',
}}>
<Text style={{fontSize: 30, color: 'green'}}>huge</Text>
generic generic generic
<Text style={{fontSize: 6, color: 'red'}}>
small small small small small small
</Text>
<Text>regular regular</Text>
<Text style={{fontSize: 30, color: 'green'}}>
huge huge huge huge huge
</Text>
generic generic generic
</AutogrowingTextInputExample>
</View>
);
},
},
{
title: 'TextInput maxLength',
render: function (): React.Node {
@@ -10,9 +10,8 @@
'use strict';
const React = require('react');
const {TextInput, View} = require('react-native');
const {useEffect, useState} = React;
import React, {useEffect, useState} from 'react';
import {TextInput, View} from 'react-native';
function TextInputKeyProp() {
const [startKey, setStartKey] = useState(0);
@@ -23,6 +23,7 @@ import {
Button,
Platform,
StyleSheet,
Switch,
Text,
TextInput,
View,
@@ -76,6 +77,9 @@ const styles = StyleSheet.create({
right: -5,
bottom: -5,
},
wrappedText: {
maxWidth: 300,
},
});
class AutoFocusWithSelectOnFocusTextExample extends React.Component<
@@ -885,6 +889,43 @@ function DynamicContentWidth() {
);
}
function AutogrowingTextInputExample({
style,
...props
}: React.ElementConfig<typeof TextInput>) {
const [multiline, setMultiline] = React.useState(true);
const [fullWidth, setFullWidth] = React.useState(true);
const [text, setText] = React.useState('');
const [contentSize, setContentSize] = React.useState({width: 0, height: 0});
return (
<View>
<RNTesterText>Full width:</RNTesterText>
<Switch value={fullWidth} onValueChange={setFullWidth} />
<RNTesterText>Multiline:</RNTesterText>
<Switch value={multiline} onValueChange={setMultiline} />
<RNTesterText>TextInput:</RNTesterText>
<ExampleTextInput
multiline={multiline}
style={[style, {width: fullWidth ? '100%' : '50%'}]}
onChangeText={setText}
onContentSizeChange={({nativeEvent}) => {
setContentSize({
width: nativeEvent.contentSize.width,
height: nativeEvent.contentSize.height,
});
}}
{...props}
/>
<RNTesterText>Plain text value representation:</RNTesterText>
<RNTesterText>{text}</RNTesterText>
<RNTesterText>Content Size: {JSON.stringify(contentSize)}</RNTesterText>
</View>
);
}
module.exports = ([
{
title: 'Auto-focus & select text on focus',
@@ -1195,4 +1236,27 @@ module.exports = ([
return <DynamicContentWidth />;
},
},
{
title: 'Auto-expanding',
render: function (): React.Node {
return (
<View style={styles.wrappedText}>
<AutogrowingTextInputExample
enablesReturnKeyAutomatically={true}
returnKeyType="done"
style={{maxHeight: 400, minHeight: 20, backgroundColor: '#eeeeee'}}>
generic generic generic
<Text style={{fontSize: 6, color: 'red'}}>
small small small small small small
</Text>
<Text>regular regular</Text>
<Text style={{fontSize: 30, color: 'green'}}>
huge huge huge huge huge
</Text>
generic generic generic
</AutogrowingTextInputExample>
</View>
);
},
},
]: Array<RNTesterModuleExample>);