Skip to content

Commit

Permalink
Merge pull request #22805 from kosmydel/@swm/refactor-keyboard-dismis…
Browse files Browse the repository at this point in the history
…sing-flat-list

Refactor KeyboardDismissingFlatList to a functional component
  • Loading branch information
marcaaron authored Jul 20, 2023
2 parents f11364f + 6f82f86 commit d34fffa
Showing 1 changed file with 35 additions and 42 deletions.
77 changes: 35 additions & 42 deletions src/components/KeyboardDismissingFlatList/index.js
Original file line number Diff line number Diff line change
@@ -1,58 +1,51 @@
import React, {Component} from 'react';
import React, {useRef, useEffect, useCallback} from 'react';
import {FlatList, Keyboard} from 'react-native';
import * as DeviceCapabilities from '../../libs/DeviceCapabilities';

class KeyboardDismissingFlatList extends Component {
constructor(props) {
super(props);
function KeyboardDismissingFlatList(props) {
const isScreenTouched = useRef(false);

this.touchStart = this.touchStart.bind(this);
this.touchEnd = this.touchEnd.bind(this);
}
const touchStart = () => {
isScreenTouched.current = true;
};

componentDidMount() {
const touchEnd = () => {
isScreenTouched.current = false;
};

useEffect(() => {
if (!DeviceCapabilities.canUseTouchScreen()) {
return;
}

// We're setting `isScreenTouched` in this listener only for web platforms with touchscreen (mWeb) where
// we want to dismiss the keyboard only when the list is scrolled by the user and not when it's scrolled programmatically.
document.addEventListener('touchstart', this.touchStart);
document.addEventListener('touchend', this.touchEnd);
}

componentWillUnmount() {
if (!DeviceCapabilities.canUseTouchScreen()) {
document.addEventListener('touchstart', touchStart);
document.addEventListener('touchend', touchEnd);

return () => {
document.removeEventListener('touchstart', touchStart);
document.removeEventListener('touchend', touchEnd);
};
}, []);

const onScroll = useCallback(() => {
// Only dismiss the keyboard whenever the user scrolls the screen
if (!isScreenTouched.current) {
return;
}

document.removeEventListener('touchstart', this.touchStart);
document.removeEventListener('touchend', this.touchEnd);
}

touchStart() {
this.isScreenTouched = true;
}

touchEnd() {
this.isScreenTouched = false;
}

render() {
return (
<FlatList
// eslint-disable-next-line react/jsx-props-no-spreading
{...this.props}
onScroll={() => {
// Only dismiss the keyboard whenever the user scrolls the screen
if (!this.isScreenTouched) {
return;
}
Keyboard.dismiss();
}}
/>
);
}
Keyboard.dismiss();
}, []);

return (
<FlatList
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
onScroll={onScroll}
/>
);
}

KeyboardDismissingFlatList.displayName = 'KeyboardDismissingFlatList';

export default KeyboardDismissingFlatList;

0 comments on commit d34fffa

Please sign in to comment.