简体   繁体   中英

react-leaflet doesn't appear after adding css

I have a map component inside rc-tabs component

import React from "react";
import {Map as LeafMap, TileLayer, Marker, Popup} from "react-leaflet";

const Map = () => {

    return (
        <div className="leaflet-appearance">
            <LeafMap center={[59.95, 30.33]} zoom={11}>
                <TileLayer
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={[59.95, 30.33]}>
                    <Popup>
                        A pretty CSS3 popup. <br/> Easily customizable.
                    </Popup>
                </Marker>
            </LeafMap>
        </div>
    )
};

export default Map

And it is rendered. Not well - some tiles are not loaded the size differs on zoom but it is visible. the pic of somehow working react-leaflet:

I want to fix it. I add a css into my index.html file

<!-- Leaflet Maps Styling  -->
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"></script>

and set a width in Map.css

.leaflet-appearance {
    height: 200px;
    width: 200px;
}

leaflet doesn't work:

How can I fix it?

Obviously you have not set a height to the map properly and also there is somethign wrong with the leaflet.css import in your code

Here is how it should be:

import React from "react";
import "rc-tabs/assets/index.css";
import "leaflet/dist/leaflet.css";
import "./styles.css";

import Tabs, { TabPane } from "rc-tabs";
import TabContent from "rc-tabs/lib/TabContent";
import ScrollableInkTabBar from "rc-tabs/lib/ScrollableInkTabBar";
import { Map as LeafMap, TileLayer, Marker, Popup } from "react-leaflet";

export default function App() {
  var callback = function(key) {};

  return (
    <Tabs
      defaultActiveKey="1"
      onChange={callback}
      renderTabBar={() => <ScrollableInkTabBar />}
      renderTabContent={() => <TabContent />}
    >
      <TabPane tab="tab 1" key="1">
        <LeafMap center={[59.95, 30.33]} zoom={11} style={{ height: "100vh" }}>
          <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
          <Marker position={[59.95, 30.33]}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
            </Popup>
          </Marker>
        </LeafMap>
      </TabPane>
      <TabPane tab="tab 2" key="2">
        second
      </TabPane>
      <TabPane tab="tab 3" key="3">
        third
      </TabPane>
    </Tabs>
  );
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM