Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active September 11, 2019 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sturmenta/b3946a1ef1d0175ad82c1b359af3c320 to your computer and use it in GitHub Desktop.
Save sturmenta/b3946a1ef1d0175ad82c1b359af3c320 to your computer and use it in GitHub Desktop.
react native KeyboardContext
import React, { PureComponent } from 'react';
import { AppNavigator, setTopLevelNavigator } from './navigation';
import { KeyboardProvider } from './utils/keyboardContext';
export default class App extends PureComponent {
render() {
return (
<KeyboardProvider>
<AppNavigator ref={navigationRef => setTopLevelNavigator(navigationRef)} />
</KeyboardProvider>
);
}
}
import * as React from 'react';
import { withKeyboardContext } from '../../utils/keyboardContext';
class Container extends React.Component {
render() {
const { isKeyboardOpen, realFullHeight } = this.props;
console.log('isKeyboardOpen',isKeyboardOpen);
console.log('realFullHeight',realFullHeight);
return ( <View style={{ height: realFullHeight }} /> );
}
}
export default withKeyboardContext(Container);
import React from 'react';
import KeyboardListener from 'react-native-keyboard-listener';
import { fullHeight } from './responsiveSize';
const initialValues = {
isKeyboardOpen: false,
realFullHeight: fullHeight,
};
const KeyboardContext = React.createContext(initialValues);
export const withKeyboardContext = Component => {
return function WrapperComponent(props) {
return (
<KeyboardContext.Consumer>
{({ isKeyboardOpen, realFullHeight }) => (
<Component {...props} realFullHeight={realFullHeight} isKeyboardOpen={isKeyboardOpen} />
)}
</KeyboardContext.Consumer>
);
};
};
export class KeyboardProvider extends React.Component {
state = initialValues;
render() {
const { isKeyboardOpen, realFullHeight } = this.state;
return (
<KeyboardContext.Provider value={{ isKeyboardOpen, realFullHeight }}>
{this.props.children}
<KeyboardListener
onWillShow={e =>
this.setState({
isKeyboardOpen: true,
realFullHeight: fullHeight - e.endCoordinates.height,
})
}
onWillHide={() => this.setState({ isKeyboardOpen: false, realFullHeight: fullHeight })}
/>
</KeyboardContext.Provider>
);
}
}
export default KeyboardContext;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment