Skip to content

Instantly share code, notes, and snippets.

@ccorcos
Created December 1, 2016 18:46
Show Gist options
  • Save ccorcos/b155a217dafab0268c90af3ea818bfd5 to your computer and use it in GitHub Desktop.
Save ccorcos/b155a217dafab0268c90af3ea818bfd5 to your computer and use it in GitHub Desktop.
class WithGps extends PureComponent {
constructor(props) {
super(props)
// see if maybe you have it cached
const gps = GeoService.get()
// this will be effective on the first render
this.state = { gps }
// wait for the gps location
if (!gps) {
GeoService.find().then((gps) => this.setState({gps}))
}
}
componentDidMount() {
// the component already rendered so if we do the same thing here,
// we'll see a loading flash even if we have the gps location cached
}
// option 1: use context
// getChildContext() {
// // https://facebook.github.io/react/docs/context.html
// return { gps }
// }
// option 2: pass a render function as props
// render() {
// const { renderWithGps, ...props } = this.props
// const { gps } = this.state
// return renderWithGps({gps, ...props})
// }
// // then you can use a helper function like this if you want:
// const withGps = (Comp) => <WithGps renderWithGps={(props) => <Comp {...props}/>}/>
// option 3: magically pass props to the immediate children
// render() {
// return React.Children.only(React.Children.map(this.props.children, (child) => {
// return React.cloneElement(child, {
// gps: this.state.gps,
// })
// }))
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment