Access object from multiple React components

Ad

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?

Ad

Answer

Ad

Create the map variable in some other Lifecycle method like componentWillMount() or componentWillReceiveProps() and assign the value of map to this.state via setState() method.

eg:

state = {map: {}}                           // defined a default state
componentWillReceiveProps(nextProps){
  map =  new mapboxgl.Map({ //your code });
  this.setState({ map: map});
}

Now, pass this.state.map as props to child MapMarker. Inside your render() method in <MapboxMap/>,

<MapMarker key={photo.id} photo={photo} map={this.state.map}/>

Now inside <MapMarker/> component the map from your parent <MapboxMap/> component will be accessible as this.props.map.

PS: Refer Component Specs and Lifecycle from React Docs for understanding where to use setState() method and where not.

Ad
source: stackoverflow.com
Ad