0

I tried the solution here Google maps in hidden div but it didn't work. Think it might be an issue with react. The map loads fine when not placed in the hidden div.

When state.hideScore turns false in the parent container, the map shows up but as a gray box. any help?

Parent container

<div hidden={this.state.hideScore}>         
<ScoreExplanation score={this.state.score} />
<br />
<ResultList data={this.state.scoreArray} />     
<ResultMap />           
</div>

Component

import React, { Component, PropTypes } from 'react';

var $ = require ('jquery');
var map;

var ResultMap = React.createClass({
  componentDidMount: function() {
    // ** Instantiating the Map ** //
    map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 14
        });

        google.maps.event.trigger(map, 'resize');
        map.setZoom( map.getZoom() );
  },
  render: function() {
    return (
      <div style={{overflow:'visible',height:'300px',width:'300px'}} id="map"></div>
    );
  }
});
export default ResultMap;
1
  • 1
    when you activate the hide div ... you should call (or recall ) or initialize the map ... is not an issue with react is for all js .. try build a initialize function you can call when show the div ... I don't know react so ... i can shhow you the code ..
    – ScaisEdge
    Commented May 13, 2016 at 21:35

1 Answer 1

1

Instead of initializing the map in componentDidMount, you should instead initialize it when the parent re-renders after calling setState to change this.state.hideScore. What's happening right now is, your map is getting loaded into the ResultMap component before its parent is visible. You should instead wait until the parent component is visible, then instantiate the ResultMap.

Example:

Parent component render method

// I prefer using CSS classes to hide/display components.
// Initialize hideScore to 'hidden' and see CSS.
render () {
  return (
    <div className={this.state.hideScore}>         
      <ScoreExplanation score={this.state.score} />
      <br />
      <ResultList data={this.state.scoreArray} />     
      <div id='result-container'></div>
    </div>
  )
}

Parent component click handler method (Can be whatever method).

handleClick = () => {
  this.setState({
    hideScore: 'shown' // See CSS.
  });
  ReactDOM.render(
    <ResultMap />,
    document.getElementById('result-container')
  );
}

CSS

.shown {
  display: block; // Or whatever is your preference.
}

.hidden {
  display: none;
}
2
  • Works, thanks! Although I had to remove the curly braces in ReactDOM.render for it to work.
    – user935618
    Commented May 16, 2016 at 20:19
  • Not sure why I had those in there. Good catch!
    – Ezra Chang
    Commented May 16, 2016 at 21:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.