Skip to content

Instantly share code, notes, and snippets.

@grabbou
Created September 13, 2015 17:10
Show Gist options
  • Save grabbou/8399c437e4b854e4184c to your computer and use it in GitHub Desktop.
Save grabbou/8399c437e4b854e4184c to your computer and use it in GitHub Desktop.
import KeyboardEvents from 'react-native-keyboardevents';
import PureRender from './pureRender';
import React, {Animated} from 'react-native';
import {autobind} from 'core-decorators';
import {Emitter as KeyboardEventEmitter} from 'react-native-keyboardevents';
export default function makeDecorator(factor = 2.5) {
return function trackKeyboard(Component) {
@PureRender
class TrackKeyboard extends React.Component {
state = {
keyboardSpace: new Animated.Value(0),
keyboardOpacity: new Animated.Value(1),
isKeyboardOpened: false
}
componentDidMount() {
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.on(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
}
componentWillUnmount() {
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillShowEvent, this.updateKeyboardSpace);
KeyboardEventEmitter.off(KeyboardEvents.KeyboardWillHideEvent, this.resetKeyboardSpace);
}
@autobind
updateKeyboardSpace(frames) {
this.setState({
isKeyboardOpened: true
});
Animated.parallel([
Animated.spring(this.state.keyboardSpace, {
toValue: -frames.end.height / factor
}),
Animated.spring(this.state.keyboardOpacity, {
toValue: 0
})
]).start();
}
@autobind
resetKeyboardSpace() {
this.setState({
isKeyboardOpened: false
});
Animated.parallel([
Animated.spring(this.state.keyboardSpace, {
toValue: 0
}),
Animated.spring(this.state.keyboardOpacity, {
toValue: 1
})
]).start();
}
render() {
const animations = {
slideUp: {
transform: [{translateY: this.state.keyboardSpace}]
},
fadeOut: {
opacity: this.state.keyboardOpacity
}
};
return (
<Component animations={animations} {...this.props} {...this.state} />
);
}
}
return TrackKeyboard;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment