Skip to content

Commit

Permalink
feat(withGoogleMap): revamp with prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
tomchentw committed Sep 13, 2017
1 parent 13cbef2 commit c3de3b3
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 104 deletions.
104 changes: 0 additions & 104 deletions src/lib/withGoogleMap.js

This file was deleted.

91 changes: 91 additions & 0 deletions src/withGoogleMap.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/* global google */
import _ from "lodash"
import warning from "warning"
import invariant from "invariant"
import { getDisplayName, createEagerFactory } from "recompose"
import PropTypes from "prop-types"
import React from "react"
import { MAP } from "./constants"

export default function withGoogleMap(BaseComponent) {
const factory = createEagerFactory(BaseComponent)

class Container extends React.PureComponent {
static displayName = `withGoogleMap(${getDisplayName(BaseComponent)})`

static propTypes = {
containerElement: PropTypes.node.isRequired,
mapElement: PropTypes.node.isRequired,
}

static childContextTypes = {
[MAP]: PropTypes.object,
}

state = {
map: null,
}

handleComponentMount = _.bind(this.handleComponentMount, this)

getChildContext() {
return {
[MAP]: this.state.map,
}
}

componentWillMount() {
const { containerElement, mapElement } = this.props
invariant(
!!containerElement && !!mapElement,
`Required props containerElement or mapElement is missing. You need to provide both of them.
The \`google.maps.Map\` instance will be initialized on mapElement and it's wrapped by\
containerElement.\nYou need to provide both of them since Google Map requires the DOM to\
have height when initialized.`
)
}

handleComponentMount(node) {
if (this.state.map || node === null) {
return
}
warning(
`undefined` !== typeof google,
`Make sure you've put a <script> tag in your <head> element to load Google Maps JavaScript API v3.
If you're looking for built-in support to load it for you, use the "async/ScriptjsLoader" instead.
See https://github.com/tomchentw/react-google-maps/pull/168`
)
// https://developers.google.com/maps/documentation/javascript/3.exp/reference#Map
const map = new google.maps.Map(node)
this.setState({ map })
}

render() {
const { containerElement, mapElement, ...restProps } = this.props

const { map } = this.state

if (map) {
return React.cloneElement(
containerElement,
{},
React.cloneElement(mapElement, {
ref: this.handleComponentMount,
}),
<div>{factory(restProps)}</div>
)
} else {
return React.cloneElement(
containerElement,
{},
React.cloneElement(mapElement, {
ref: this.handleComponentMount,
}),
<div />
)
}
}
}

return Container
}

0 comments on commit c3de3b3

Please sign in to comment.