Skip to content

Instantly share code, notes, and snippets.

@sturmenta
Last active Sep 11, 2019
Embed
What would you like to do?
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