I have a MapboxMap
React component that initialises and renders a Mapbox map (under the map
const), and needs to render MapMarker
components inside of it.
This is what MapboxMap
looks like:
import React from 'react'
import ReactDOM from 'react-dom'
import MapMarker from './MapMarker'
const MapboxMap = React.createClass({
componentDidMount(argument) {
mapboxgl.accessToken = 'access_token'
// This is what I want to access from inside of <MapMarker />
const map = new mapboxgl.Map({
container: ReactDOM.findDOMNode(this),
style: 'mapbox://styles/mapbox/streets-v8',
center: [-74.50, 40],
zoom: 9
})
},
render() {
const errors = this.props.errors
const photos = this.props.photos
return (
<div className='map'>
{errors.length > 0 && errors.map((error, index) => (
<pre key={index}>Error: {error}</pre>
))}
{errors.length === 0 && photos.map(photo => (
<MapMarker key={photo.id} photo={photo} />
))}
</div>
)
}
})
module.exports = MapboxMap
This is what MapMarker
looks like.
import React from 'react'
import ReactDOM from 'react-dom'
import MapboxMap from './MapboxMap'
const MapMarker = React.createClass({
render() {
const photo = this.props.photo
console.log(photo)
// I want to be able to access `map` inside of this component
return (
<div className='marker'></div>
)
}
})
module.exports = MapMarker
How can I structure my two components so that I can access map
from both components, but specifically render the map inside of the MapboxMap
component?
Create the
map
variable in some other Lifecycle method likecomponentWillMount()
orcomponentWillReceiveProps()
and assign the value of map tothis.state
viasetState()
method.eg:
Now, pass
this.state.map
as props to child MapMarker. Inside yourrender()
method in<MapboxMap/>
,Now inside
<MapMarker/>
component the map from your parent<MapboxMap/>
component will be accessible asthis.props.map
.PS: Refer Component Specs and Lifecycle from React Docs for understanding where to use
setState()
method and where not.Naisheel Verdhan's approach is good. I'd make one suggestion on top of that. Instead of setting the state in
componentWillMount()
orcomponentWillReceiveProps()
, you can do it ingetInitialState()
(React.createClass
syntax) or in the constructor() (ES2015,class extends React.Component
syntax).