Display the marker icon when using react-leaflet

Initially, the marker icon after installing react-leaflet shows a broken image. To fix it, import L from leaflet and the icon from leaflet/dist/images/:

jsx
import React, { useEffect, useState }             from 'react'
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'
import L                                          from 'leaflet'
import icon                                       from 'leaflet/dist/images/marker-icon.png';
import 'leaflet/dist/leaflet.css'

const LeafletMap = () => {

    L.Marker.prototype.options.icon = L.icon({ iconUrl: icon })

    return(
        <MapContainer center = {[41.39, 2.10]} zoom = {18} scrollWheelZoom = {false} style = {{ height: '270px', width: '270px' }}>
            <TileLayer
                url = "https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}"
            />
            <Marker position = {[41.39, 2.10]}>
                <Popup>
                A pretty CSS3 popup. <br /> Easily customizable.
                </Popup>
            </Marker>
        </MapContainer>
    )

}

export default LeafletMap

If you want to add a custom icon:

jsx
// Import the custom marker
import marker from '../icons/marker.png'

// Add the URL 
L.Marker.prototype.options.icon = L.icon({ iconUrl: marker })

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.