Skip to content

Instantly share code, notes, and snippets.

@Lepozepo
Created January 13, 2017 16:29
Show Gist options
  • Save Lepozepo/79594a7974dd8bc785cffd8b36b0285d to your computer and use it in GitHub Desktop.
Save Lepozepo/79594a7974dd8bc785cffd8b36b0285d to your computer and use it in GitHub Desktop.
React without Context Coupling
import { Component } from 'react';
import { ScrollView, TextInput } from 'react-native';
// Parent Component
class Card extends Component {
handleFocus = (y) => {
this.scrollView.scrollTo({ y });
}
render() {
const {children} = this.props;
return (
<ScrollView ref={(r) => {this.scrollView = r}}>
{children}
</ScrollView>
);
}
}
// Child Component
class CardTextInput extends Component {
handleFocus = () => {
if (!this.props.onFocus) return;
this.props.onFocus(this.yPosition);
}
handleLayout = ({nativeEvent:{layout:{ y }}}) => {
this.yPosition = y;
}
render() {
return (
<TextInput
onLayout={this.handleLayout}
onFocus={this.handleFocus}
/>
);
}
}
// A developer using your weak non-contextual component
class Cards extends Component {
render() {
return (
<Card ref={(r) => {this.card = r;}}>
<CardTextInput
onFocus={this.card && this.card.handleFocus}
/>
</Card>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment