Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make react-leaflet map component resize itself to fit available space

Setting the width of the Map component works, but height seems to only respond to an absolute size in pixels.

Is it possible to make the map control automatically consume available space inside the parent element?

like image 378
Bjorn Reppen Avatar asked Dec 19 '22 10:12

Bjorn Reppen


2 Answers

I was able to create a component that passed in a component state value for the height of the map. I created a helper function that would resize the height to make it all responsive.

...

export default class MapContainer extends React.Component {

  updateDimensions() {
    const height = window.innerWidth >= 992 ? window.innerHeight : 400
    this.setState({ height: height })
  }

  componentWillMount() {
    this.updateDimensions()
  }

  componentDidMount() {
    window.addEventListener("resize", this.updateDimensions.bind(this))
  }

  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions.bind(this))
  }

  ...

  render() {
    ...
    return (
      <div class="map-container" style={{ height: this.state.height }}>
        <Map>
          ...
        </Map>
      </div>
    )
  }
}
like image 75
Evan Siroky Avatar answered May 17 '23 12:05

Evan Siroky


I solved this by using the react-container-dimensions component, which passes width/height as props to its child:

<div className="div that can resize""
ContainerDimensions>
<MyMapContainer/>
</ContainerDimensions>
</div>

...

style.width = Math.floor(this.props.width);                                                                                                                                                                                                                                                                                              
return (                                                                                                                                                                          
  <Map style={style}
like image 27
ahota Avatar answered May 17 '23 13:05

ahota