How to import and use Leaflet (client side library)?

Hi, I’m trying to import and use the React Leaflet library. But it uses window. So I tried dynamic import.

actions: {
        theme: {
            beforeCSR: async ({ libraries }) => {
                const { MapContainer, TileLayer, Marker, Popup } = await import(
                    "react-leaflet"
                );

                libraries.MapContainer = MapContainer;
                libraries.TileLayer = TileLayer;
                libraries.Marker = Marker;
                libraries.Popup = Popup;
            },
        },
    },

Then I want to access the library in the “CustomMap” component like this:

import React from "react";
import { connect, css } from "frontity";

const CustomMap = ({ libraries }) => {
    const { MapContainer, TileLayer, Marker, Popup } = libraries;

    if (MapContainer && TileLayer && Marker && Popup) {
        return (
            <MapContainer
                center={[50, 100]}
                zoom={15}
                attributionControl={false}
                css={css`
                    margin-top: 24px;
                `}
            >
                <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />

                <Marker position={[50, 100]}>
                    <Popup>Popup</Popup>
                </Marker>
            </MapContainer>
        );
    } else {
        return null;
    }
};

export default connect(CustomMap);

I get this error:

Warning: Expected server HTML to contain a matching <div> in <div>.at div at MapContainer 

How to import such a library correctly?

Hi @Paulius, this reply arrives probably too late, but I’d suggest you do:

import { loadable } from 'frontity';
const CustomMap = loadable(() => import('./custom-map'), { ssr: false });
// custom-map.js
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';

const CustomMap = () => {
...
}

export default CustomMap;

This will load the component that is using Leaflet only on client side.