Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-leaflet with react-bootstrap tabs #40

Closed
michaeljones opened this issue Jun 9, 2015 · 7 comments
Closed

react-leaflet with react-bootstrap tabs #40

michaeljones opened this issue Jun 9, 2015 · 7 comments

Comments

@michaeljones
Copy link

Hi,

Thanks for the project. I really appreciate being able to use it for my web app.

I am attempting to have a map inside a tab using react-bootstrap tabs. The tab is not selected by at load but it seems that the react-bootstrap implementation still initialises the tab contents with the Map component. When I do change to the tab with the map, the map tiles have not loaded properly and they seem to struggle to load properly as I pan around the map (only some tiles load.) If I change the application to load that tab initially then to map works perfectly.

The react bootstrap tabs have a fade out & in behaviour as you switch tabs, which might affect things. I'm not sure.

Is this something you are familiar with? Can you offer advice or would you have time to look at it if I provide example set up that shows the issue?

I have some react experience but I'm new to Leaflet and I'm not sure where to begin with figuring this out.

Cheers,
Michael

@PaulLeCam
Copy link
Owner

Hi, thanks!

I have never had this use case so I don't know what can be the exact origin, can you setup a jsbin or something showing the issue please?

@michaeljones
Copy link
Author

Thanks for the quick response. It is a pretty niche problem! I'll try to reproduce it for you somewhere public.

@michaeljones
Copy link
Author

I'm afraid I don't know how to reproduce it in an environment like jsbin as I don't know how to get react-bootstrap & react-leaflet without npm. The code required for a simple demo is below:

index.html

<!DOCTYPE html>
<html>
    <head>
        <script src="https://fb.me/react-with-addons-0.13.3.js"></script>
        <script src="https://code.jquery.com/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" type="text/css" />

        <!-- Leaflet Maps Styling  -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.3/leaflet.css">

        <meta charset="utf-8">
        <title>Tabbed Map Example</title>

    </head>
    <body>

        <div id="tab-container"></div>

        <script type="text/javascript" src="demo.js"></script>

    </body>

</html>

app.js

var React = require('react');
var TabbedArea = require('react-bootstrap/lib/TabbedArea');
var TabPane = require('react-bootstrap/lib/TabPane');
const position = [51.5072, -0.1275];
const style = { height: '400px' };
const zoom = 5;

const tabbedAreaInstance = (
  <TabbedArea defaultActiveKey={1}>
    <TabPane eventKey={1} tab='Default Tab'>
        <Map center={position} zoom={zoom} style={style}>
            <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              />
            <Marker position={position}>
                <Popup>
                    <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                </Popup>
            </Marker>
        </Map>
    </TabPane>
    <TabPane eventKey={2} tab='Map Tab'>
        <Map center={position} zoom={zoom} style={style}>
            <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
              attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
              />
            <Marker position={position}>
                <Popup>
                    <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                </Popup>
            </Marker>
        </Map>
    </TabPane>
  </TabbedArea>
);

React.render(tabbedAreaInstance, document.getElementById('tab-container'));

browserify command

browserify app.js -t babelify --outfile demo.js

You'll need to npm install react-bootstrap, react and react-leaflet. Sorry I couldn't make it easier. Does that seem reasonable?

The demo has a set up with two tabs. I've put maps in both tabs to show that it loads properly in the default tab but when you switch to the other tab the tiles do not load properly, even when you pan around a bit it seems confused.

I'm using Chrome 43 on Ubuntu.

I hope that is sufficient but please ask if there are details I've missed.

Michael

@PaulLeCam
Copy link
Owner

Hi,

It seems to be a known issue with Leaflet, if its container size is changed or if it's not visible when the map is created. Calling map.invalidateSize() resets the map display.

Here is an example to make it work with react-bootstrap:

class MapTabs extends React.Component {
  constructor() {
    super();
    this.state = {
      key: 1
    };
  }

  onSelect(key) {
    this.setState({key});
    setTimeout(() => {
      this.refs['map' + key].getLeafletElement().invalidateSize(false);
    }, 300); // Adjust timeout to tab transition
  }

  render() {
    return (
      <TabbedArea activeKey={this.state.key} onSelect={this.onSelect.bind(this)}>
        <TabPane eventKey={1} tab='Default Tab'>
            <Map ref="map1" center={position} zoom={zoom} style={style}>
                <TileLayer
                  url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                  attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                  />
                <Marker position={position}>
                    <Popup>
                        <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                    </Popup>
                </Marker>
            </Map>
        </TabPane>
        <TabPane eventKey={2} tab='Map Tab'>
            <Map ref="map2" center={position} zoom={zoom} style={style}>
                <TileLayer
                  url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                  attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                  />
                <Marker position={position}>
                    <Popup>
                        <span>A pretty CSS3 popup.<br/>Easily customizable.</span>
                    </Popup>
                </Marker>
            </Map>
        </TabPane>
      </TabbedArea>
    );
  }
}

The trick is to control the tabs from a parent component, this way you can access the relevant <Map> via its ref, and call invalidateSize() after the tab is fully displayed. That's why there is a 300ms timeout before calling the function.
If the tabs transition has a different timing, you should adjust this timeout, making sure it's always superior or equal to the transition time, otherwise the map rendering would not be done properly.

@michaeljones
Copy link
Author

Wow, thank you for investigating and for the explaining. Kind of you to give such a clear run down. I will attempt to integrate this approach into my set up.

I guess I'll close this ticket as there isn't really an action point for it. It is such an edge case that it doesn't seem worth trying to add to the documentation for react-leaflet itself.

Much appreciated!

@Hakaze Hakaze mentioned this issue May 16, 2016
olecve added a commit to iobis/smalldata that referenced this issue May 10, 2019
it eliminates issue with wrong position of the marker and inappropriate loading of the map elements
not sure what is the main reason for this problem... the similar issue is described here
PaulLeCam/react-leaflet#40
@citizen-dror
Copy link

solution using hooks (and mobx sotre) in FunctionComponent :

parent tabs Component

interface IProps { 
    defaultKey? :string
}
export const TabsTemplate: React.FC<IProps> = observer(({defaultKey="charts"}) => {
    const [activeKey] = useState(defaultKey);
    const store = useStore();
    store.isReadyToRenderMap = false;
    return (
        <Tabs defaultActiveKey={activeKey} id="main-tabs"
            onSelect={(activeKey: any) => {
                if (activeKey === "map") {
                    //map is renderd only when tab is shown
                    store.isReadyToRenderMap = true;
                }
            }}
        >
            <Tab eventKey="charts" title={"Charts"}>
                <GroupByGraphsPanel />
            </Tab>
            <Tab eventKey="map" title={"Map"}>
                <MyMap />
            </Tab>
        </Tabs>
    )
})

child map Component

const MyMap : FunctionComponent<IProps> = observer(() => {
  const mapRef = useRef<any>();
  const store = useStore();
  const reactMapCenter = toJS(store.mapCenter);
  const WRAPPER_STYLES = { height: '500px', width: '100vw', maxWidth: '100%' };
  const didMountRef = useRef(false) 
  useEffect(() => {
    if (didMountRef.current) { 
      if (mapRef.current) {
        //mapRef.current  = true - like componentDidUpdate
        //this event is fierd when parent tab is shown - help render map 
        mapRef.current.leafletElement.invalidateSize(false);
      }
    } 
    else didMountRef.current = true
  })
  return (
    <div>
        <Map ref={mapRef}
          center={reactMapCenter}
          zoom={13}
          style={WRAPPER_STYLES}
        >
          <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <AccidentsMarkers />
        </Map>
        {store.isReadyToRenderMap?"":""}
    </div>
  )
})

iperdomo added a commit to akvo/akvo-lumen that referenced this issue Mar 13, 2020
Delay the call to `invalidateSize()` so the parent has the new dimension.

When we trigger the `renderLeafletMap` on `componentDidMount` and
`UNSAFE_componentWillReceiveProps` the dimensions of the parent container
element are the *old* ones.

Found it via:

    let parent = this.leafletMapNode.parentElement;
    console.log(parent.clientHeight, parentclientWidth);

More info:

    PaulLeCam/react-leaflet#40
@silverpedak
Copy link

silverpedak commented Feb 2, 2023

To anyone struggling with the map not rendering properly when using react-leaflet with reactstrap tabs, this is what worked for me.

<MapContainer
    id="map-container"
    style={{ height: "50vh" }}
    center={[40, 20]}
    zoom={2}
  >
    <TileLayer
      attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <ResizeMap />
  </MapContainer>```
const ResizeMap = () => {
  const map = useMap();
  const resizeObserver = new ResizeObserver(() => {
    map.invalidateSize();
  });
  const container = document.getElementById("map-container");
  resizeObserver.observe(container!);

  return null;
};

Found this stackoverflow ANSWER helpful which initially didn't work because the whenReady prop will not let you use the Map instance as described in the answer.

Instead, <MapContainer /> will pass the Map instance to it's children elements as described in the React-leaflet docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants