Trying to display a marker where clicked on React Leaflet map

Here’s the entire piece of code.

import React, { useState } from "react";
import { Marker, Popup, useMapEvents } from "react-leaflet";

const AddMarkers = () => {
  const [markers, setMarkers] = useState([
    {
      lat: 40,
      lng: -95.6268544,
    },
  ]);

  const map = useMapEvents({
    click: (e) => {
      setMarkers([...markers, e.latlng]);
    },
  });
  return (
    <>
      {/* {markers.map((marker, i) => {
        <Marker key={`marker-${i}`} position={marker}>
          <Popup>
            <span>
              A pretty CSS3 popup. <br /> Easily customizable.
            </span>
          </Popup>
        </Marker>;
      })} */}
      <Marker position={markers[0]}>
        <Popup>
          <span>
            A pretty CSS3 popup. <br /> Easily customizable.
          </span>
        </Popup>
      </Marker>
    </>
  );
};

export default AddMarkers;

The current ACTIVE (look at what’s commented out) piece of code works for showing just one marker. But when you uncomment this part

      {/* {markers.map((marker, i) => {
        <Marker key={`marker-${i}`} position={marker}>
          <Popup>
            <span>
              A pretty CSS3 popup. <br /> Easily customizable.
            </span>
          </Popup>
        </Marker>;
      })} */}

and comment out this part.

      <Marker position={markers[0]}>
        <Popup>
          <span>
            A pretty CSS3 popup. <br /> Easily customizable.
          </span>
        </Popup>
      </Marker>

It doesn’t work. I am trying to be able to add multiple markers to the map by appending to the markers array on a click, and then mapping over the array to display each marker one by one.

Answer

If this is your exact code, this is a simple syntax error:

{markers.map((marker, i) => { // <----- curly brace bad
  <Marker key={`marker-${i}`} position={marker}>
    <Popup>
      <span>
        A pretty CSS3 popup. <br /> Easily customizable.
      </span>
    </Popup>
  </Marker>;
})}

You’re not returning anything from the map statement. It should be

{markers.map((marker, i) => (  // <---- parantheses good
  <Marker key={`marker-${i}`} position={marker}>
    <Popup>
      <span>
        A pretty CSS3 popup. <br /> Easily customizable.
      </span>
    </Popup>
  </Marker>;
))}

Working codesandbox