I am using React Leaflet to render Leaflet map and its GeoJSON component to render polygons. I am trying to implement dragging multiple polygons together at once, as a group.
I added Leaflet.Path.Drag library and tried to reuse this code. I am able to get transformation matrix which is in parent's state. If I want to apply this matrix to multiple polygons with _transform method, it doesn't work. I think the reason is that matrix is not applied to correct layers, but I have no idea how to fix this.
codesandbox.io
App.js
import React from "react";
import { MapContainer, GeoJSON, TileLayer } from "react-leaflet";
import { geoJson, latLngBounds } from "leaflet";
import "./styles.css";
import "leaflet/dist/leaflet.css";
import { GeoJsonContainer } from "./GeoJsonContainer";
const objects = [
{
polygon: {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
type: "Polygon",
coordinates: [
[
[-104.98569488525392, 39.63431579014969],
[-104.98569488525392, 39.64165260123419],
[-104.97161865234376, 39.64165260123419],
[-104.97161865234376, 39.63431579014969]
]
]
}
}
]
}
},
{
polygon: {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
type: "Polygon",
coordinates: [
[
[-105.02964019775392, 39.6206315500488],
[-105.02964019775392, 39.65685252543906],
[-104.99067306518556, 39.65685252543906],
[-104.99067306518556, 39.6206315500488]
]
]
}
}
]
}
}
];
const getPolygonPointFromBounds = (latLngBounds) => {
const center = latLngBounds.getCenter();
const latlngs = [];
latlngs.push(latLngBounds.getSouthWest()); //bottom left
latlngs.push({ lat: latLngBounds.getSouth(), lng: center.lng }); //bottom center
latlngs.push(latLngBounds.getSouthEast()); //bottom right
latlngs.push({ lat: center.lat, lng: latLngBounds.getEast() }); // center right
latlngs.push(latLngBounds.getNorthEast()); //top right
latlngs.push({
lat: latLngBounds.getNorth(),
lng: latLngBounds.getCenter().lng
}); //top center
latlngs.push(latLngBounds.getNorthWest()); //top left
latlngs.push({
lat: latLngBounds.getCenter().lat,
lng: latLngBounds.getWest()
}); //center left
return latlngs;
};
export default function App() {
const [matrix, setMatrix] = React.useState(null);
let newBounds = [];
let selectBoundingBox = [];
objects.forEach((building) => {
const polygonBounds = geoJson(building.polygon).getBounds();
newBounds = [...newBounds, polygonBounds];
});
const polygonPoints = getPolygonPointFromBounds(latLngBounds(newBounds));
const convertedData = polygonPoints.map((point) => [point.lng, point.lat]);
convertedData.push([polygonPoints[0].lng, polygonPoints[0].lat]);
selectBoundingBox = convertedData;
let selectBoxData = null;
if (selectBoundingBox) {
selectBoxData = {
type: "FeatureCollection",
features: [
{
type: "Feature",
properties: {},
geometry: {
type: "Polygon",
coordinates: [selectBoundingBox]
}
}
]
};
}
const handleFeature = (layer) => {
layer.makeDraggable();
layer.dragging.enable();
layer.on("drag", function (e) {
setMatrix(layer.dragging._matrix);
});
};
return (
<MapContainer center={[39.63563779557324, -104.99234676361085]} zoom={12}>
<TileLayer
attribution='© OpenStreetMap contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
{objects.map((object, i) => (
<GeoJsonContainer data={object} key={i} matrix={matrix} />
))}
<GeoJSON
data={selectBoxData}
style={() => ({
color: "green",
weight: 3,
opacity: 0.5
})}
draggable={true}
onEachFeature={(feature, layer) => handleFeature(layer)}
></GeoJSON>
</MapContainer>
);
}
GeoJsonContainer.js
import React from "react";
import { GeoJSON } from "react-leaflet";
require("leaflet-path-drag");
export const GeoJsonContainer = (props) => {
const geoJSONRef = React.useRef(null);
const layerRef = React.useRef(null);
React.useEffect(() => {
if (geoJSONRef?.current?._layers) {
console.log("mount layers", geoJSONRef.current?._layers);
}
}, []);
React.useEffect(() => {
if (geoJSONRef?.current._layers && props.matrix) {
console.log("transform layers", geoJSONRef.current._layers);
const key = Object.keys(geoJSONRef.current._layers)[0];
const geoJSONElementLayer = geoJSONRef.current._layers[key];
if (geoJSONElementLayer) {
console.log("geoJSONElementLayer", geoJSONElementLayer);
console.log("layerRef.current", layerRef.current);
geoJSONElementLayer._transform(props.matrix);
layerRef.current._transform(props.matrix);
}
}
}, [props.matrix]);
const handleFeature = (layer) => {
console.log("handleFeature layer", layer);
layerRef.current = layer;
layer.makeDraggable();
layer.dragging.enable();
};
return (
<GeoJSON
ref={geoJSONRef}
data={props.data.polygon}
style={() => ({
color: "#3388ff",
weight: 3,
opacity: 1
})}
dragging={true}
onEachFeature={(feature, layer) => handleFeature(layer)}
></GeoJSON>
);
};
Regarding
If I want to apply this matrix to multiple polygons with _transform
method, it doesn't work
This is the expected behavior in React since matrix prop needs to be immutable meaning a new array needs to be passed each time there is a change:
layer.on("drag", function (e) {
setMatrix([...layer.dragging._matrix]);
});
instead of:
layer.on("drag", function (e) {
setMatrix(layer.dragging._matrix);
});
This way GeoJsonContainer component should get re-rendered as expected.
Another matter concerns Leaflet.Path.Drag plugin, according to the referenced thread, in fact both drop and dropend events needs to be captured to properly apply transformation, so maybe instead of matrix prop, introduce a transform prop to keep matrix array and a flag to determine whether drop or is dropend event is triggered:
const handleFeature = (layer) => {
layer.makeDraggable();
layer.dragging.enable();
layer.on("drag", function (e) {
setTransform({matrix: layer.dragging._matrix, "end": false});
});
layer.on("dragend", function (e) {
setTransform({matrix: layer.dragging._matrix, "end": true});
});
};
and pass it into GeoJsonContainer component to apply geometry transform:
React.useEffect(() => {
if (props.transform) {
geoJSONRef.current.eachLayer((layer) => {
if (props.transform.end) dragDropTransform(layer);
else __dragTransform(layer);
});
}
}, [props.transform]);
where
function __dragTransform(layer) {
layer._transform(props.transform.matrix);
}
function dragDropTransform(layer) {
layer.dragging._transformPoints(props.transform.matrix);
layer._updatePath();
layer._project();
layer._transform(null);
}
Updated live demo
A possible improvement(s):
in the provided example two instances of JSON layers are instantiated, maybe to consider create a single instance of GeoJSON and apply a style per geometry?
Solution improvements proposal
In the provided example two layers are instantiated:
in App component
GeoJSON layer which renders a single outer geometry (polygon)
and in GeoJsonContainer component another one
GeoJSON layer which in turn renders a two inner geometries (polygons)
How about to merge both GeoJSON objects, something like this:
const dataSource = {...selectBoxData,...objects[0],...objects[1]}
and create a single layer instead:
<GeoJSON data={dataSource}></GeoJSON>
This way twice initialization for dragable layers could be avoided (refactoring of duplicated code)
Related
I am trying to use geoJson layer and pass it the selectedCountry .
I get this error : "BordersGeoJSON.js:8 Uncaught TypeError: Cannot read properties of undefined (reading 'geoJSON')"
I have checked that selectedCountry is a valid geoJSON object. The console log looks like this:
{type: 'Feature', properties: {…}, geometry: {…}}
geometry
:
{type: 'Polygon', coordinates: Array(1)}
properties
:
{name: 'Ireland', iso_a2: 'IE', iso_a3: 'IRL', iso_n3: '372'}
type
:
"Feature"
[[Prototype]]
:
Object
My code is this:
import { useEffect } from 'react';
import { L } from 'leaflet';
const BordersGeoJSON = ({mapRef, selectedCountry}) => {
useEffect(() => {
if (mapRef && selectedCountry) {
console.log(selectedCountry)
const layer = L.geoJSON(selectedCountry, {
style: () => ({ color: "red" }),
});
layer.addTo(mapRef.leafletElement);
}
}, [mapRef, selectedCountry]);
return null;
};
export default BordersGeoJSON
I have tried to use selectedCountry geometry only but I get the same error
I have tried using directly the geoJSON file instead of selectedCountry but I get the same error
Here it is on sandbox : https://codesandbox.io/s/vigilant-galois-7y1xd3?file=/src/components/leaflet/BasicMap/PointsOfInterest.js
I got it working.
I have changed things to use GeoJson component and use the selectedCountry state. GeoJson needs a key to update every time selectedCountry changes .
here is the code :
import { useEffect, useState } from 'react';
import {GeoJSON } from 'react-leaflet';
const BordersGeoJSON = ({bounds, selectedCountry}) => {
const [geoJsonKey, addToGeoJsonKey] = useState(1);
useEffect(() => {
addToGeoJsonKey(geoJsonKey + 1)
}, [selectedCountry])
return (
<>
{ selectedCountry &&
<GeoJSON
key={geoJsonKey}
data={selectedCountry}
style={() => ({ color: 'blue' })}
/>
}
</>
);
};
export default BordersGeoJSON
I am trying to add a custom transform control to geoman, to do certain transformations with polylines and polygons. I see that on edit, geoman draws hint lines above vertices etc. I would like my tool to highlight polylines/polygons with the same type of hints. Below is the skeleton of my action:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
changeConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (layer.feature && layer.feature.geometry.type === 'Point') {
layer._icon.style['pointer-events'] = 'auto';
}
});
}
Is there an internal function or something that I could use to outline shapes? When I enable Edit layers tool already built into the geoman, shapes are outlined for me. How could I achieve this from my code without having to reimplement the entire thing?
Thus far, after quickly reviewing geoman code, I was able to come up with:
const ConvertAction = L.Toolbar2.Action.extend({
options: {
toolbarIcon: {
html:
'<div class="icon-maps icon-convert" title="Convert point"></div>',
tooltip: 'Convert point'
}
},
addHooks: () => {
// draw polygon
// map.pm.enableDraw();
if (!convert) changeConvert();
else disableConvert();
}
});
function changeConvert() {
convert = true;
map.eachLayer(function (layer) {
if (
layer?.feature?.geometry.type === 'Polygon' ||
layer?.feature?.geometry.type === 'LineString'
) {
const coords = layer.getLatLngs();
const markerGroup = new L.LayerGroup();
markerGroup._pmTempLayer = true;
const createMarker = (latlng) => {
const marker = new L.Marker(latlng, {
draggable: true,
icon: L.divIcon({ className: 'marker-icon' })
});
layer.options.pane =
(map.pm.globalOptions.panes &&
map.pm.globalOptions.panes.vertexPane) ||
'markerPane';
marker._pmTempLayer = true;
markerGroup.addLayer(marker);
return marker;
};
const handleRing = (coordsArr) => {
// if there is another coords ring, go a level deep and do this again
if (Array.isArray(coordsArr[0])) {
return coordsArr.map(handleRing, this);
}
// the marker array, it includes only the markers of vertexes (no middle markers)
const ringArr = coordsArr.map(createMarker);
return ringArr;
};
const markers = handleRing(coords);
map.addLayer(markerGroup);
}
});
}
function disableConvert() {
convert = false;
map.eachLayer(function (layer) {
if (
layer.dragging &&
layer.options?.draggable === true &&
layer._pmTempLayer === true
) {
console.log('temp layer:', layer);
map.removeLayer(layer);
}
});
update();
}
Seems like an excessive amount of code, and reimplementation [and probably not as good the geoman version as I don't fully understand geoman code by far] of existing functionality.
How do I simplify/fix this?
I've been trying to render a Map using #react-google-maps/api": "^2.12.1 in my react-hook-form": "^7.33.1. The requirement was to show the map onClick of the input, and the user should draw a polygon on the Map using Drawing Manager.
This is my code, I've been trying to get this working from past two days and I'm nowhere near to the solution. I've gone through stack overflow questions but most of the answers were outdated or I couldn't find anything since most of the people are using react-google-maps where it has been completely redesigned to #react-google-maps/api": "^2.12.1.
The weird thing is the exact code is working in codesandbox. I don't know what I'm
doing wrong here.
import React from "react";
import ReactDOM from "react-dom";
import { LoadScript, GoogleMap, DrawingManager } from "#react-google-maps/api";
const containerStyle = {
width: "400px",
height: "400px",
};
const API_KEY = "";
export default function GoogleMaps() {
const [state, setState] = React.useState({
drawingMode: "polygon",
});
const noDraw = () => {
setState(function set(prevState) {
return Object.assign({}, prevState, {
drawingMode: "maker",
});
});
};
return (
<div className="App">
<LoadScript
id="script-loader"
googleMapsApiKey={API_KEY}
libraries={["drawing"]}
language="en"
region="us"
>
<GoogleMap
mapContainerClassName={containerStyle}
center={{
lat: 38.9065495,
lng: -77.0518192,
}}
zoom={10}
version="weekly"
>
<DrawingManager
drawingMode={state.drawingMode}
options={{
drawingControl: true,
drawingControlOptions: {
drawingModes: ["polygon"],
},
polygonOptions: {
fillColor: `#2196F3`,
strokeColor: `#2196F3`,
fillOpacity: 0.5,
strokeWeight: 2,
clickable: true,
editable: true,
draggable: true,
zIndex: 1,
},
}}
onPolygonComplete={(poly) => {
/*const polyArray = poly.getPath().getArray();
let paths = [];
polyArray.forEach(function(path) {
paths.push({ latitude: path.lat(), longitude: path.lng() });
});
console.log("onPolygonComplete", polyArray);*/
console.log("onPolygonComplete", poly);
noDraw();
}}
/*onOverlayComplete={poly => {
const polyArray = poly.getPath().getArray();
let paths = [];
polyArray.forEach(function(path) {
paths.push({ latitude: path.lat(), longitude: path.lng() });
});
console.log("onOverlayComplete", polyArray);
}}*/
/>
</GoogleMap>
</LoadScript>
</div>
);
}
I have two leaflet maps which are loaded with geojson on the basis of a search button click. This shows some polygons with a style opacity 0.3 so you can see the street names under the polygons.
It works great except that any additional searches and loading of polygons starts to change the opacity of the polygon, making it more solid so you cant read the names of the streets under the polygon.
I try clearing the geojson layer before adding to the map, but the issue persists.
I have created a rough code pen of the issue here:
https://codepen.io/joomkit/pen/xxXgLPJ?editors=1111
Essentially just click the search button to load the layer no need to fill the listener runs a function and gets static data.
I have tried various methods to remove layer. A second click on the search is meant to clear the layer and load a new one. In the example it's just reloading the original data but the opacity is clearly demonstrated.
Main code is also below.
var geoMap2;
var lamap = new L.Map("map2", {
center: new L.LatLng(51.44094723464765, 0.048892332250943187),
// center: new L.LatLng(39.75621,-104.99404),
zoom: 14,
maxZoom: 18
});
var osm2 = L.tileLayer(
"https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png",
{
attribution:
'© OpenStreetMap contributors © CARTO',
subdomains: "abcd",
maxZoom: 18
}
);
lamap.addLayer(osm2);
searchButton.addEventListener("click", function (e) {
let searchQuery = inputSearch.value;
// searchOpenFunding(searchQuery);
setLaMap(data);
});
function setLaMap(data) {
removeLayers();
let geojsonFeatureCollection2 = {
type: "FeatureCollection",
features: setFeatureCollection2(data)
};
geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: function myonEachFeatureLaMap(feature, layer) {
layer.myTag = "myGeoJSON";
}
}).addTo(lamap);
lamap.setMaxBounds(lamap.fitBounds(geoMap2.getBounds()));
lamap.setZoom(13);
}
var removeLayers = function () {
lamap.eachLayer(function (layer) {
if (layer.myTag && layer.myTag === "myGeoJSON") {
lamap.removeLayer(layer);
console.log("rem layer from ");
}
});
};
function setFeatureCollection2(data) {
for (const [key, item] of Object.entries(data)) {
// setup lealfet geojson collection from data mapit api is incomplete pe ritem so we build it here
geoJsonFeatures2.push({
type: "Feature",
properties: {
craftentryId: item.id,
areaId: item.mapitAreaId,
lsoacode: item.lsoacode,
localauthority: item.localauthority,
openForFunding: item.openForFunding,
fundableRegion: item.fundableRegion,
title: item.title,
popupContent: ""
},
geometry: item.geojson
});
}
return geoJsonFeatures2;
}
function polyStyleLAMap(feature) {
return {
fillColor: getFillColorLaMap(feature.properties.openForFunding),
weight: 1,
opacity: 1,
color: getBorderColor(feature.properties.openForFunding),
dashArray: "0",
fillOpacity: 0.3
};
}
function getFillColorLaMap(d) {
return d === true ? "#FFFFFF" : d === false ? "#FED976" : "#FED976";
}
function getBorderColor(d) {
return d === true ? "#0e9c12" : d === false ? "#adabab" : "#cccccc";
}
Look here https://codepen.io
The code I modified is:
// 029A, 029C
function setLaMap(data) {
removeLayers();
let geojsonFeatureCollection2 = {
type: "FeatureCollection",
features: setFeatureCollection2(data),
};
console.log(geojsonFeatureCollection2);
const geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: function (feature, layer) {
layer.myTag = "myGeoJSON";
},
});
map.addLayer(geoMap2);
map.setMaxBounds(map.fitBounds(geoMap2.getBounds()));
// map.setZoom(13);
}
function removeLayers() {
map.eachLayer((layer) => {
if (layer.myTag && layer.myTag === "myGeoJSON") {
console.log(layer);
map.removeLayer(layer);
}
});
}
You need to keep the geojson layer in a global variable and remove it before over writing with the new layer data.
var geoMap2;
function setLaMap(data){
if(geoMap2) { // if geoMap2 is set remove it
lamap.removeLayer(geoMap2)
}
const geojsonFeatureCollection2 = {
"type": "FeatureCollection",
"features": setFeatureCollection2(data)
}
geoMap2 = L.geoJSON(geojsonFeatureCollection2, {
style: polyStyleLAMap,
onEachFeature: myonEachFeatureLaMap
})
.........
I tried to implement react-leaflet search from https://github.com/tumerorkun/react-leaflet-search but, it didn't worked.
following is my code (without including react-leaflet search). Can anyone help me with it.
Hi, I tried to implement react-leaflet search from https://github.com/tumerorkun/react-leaflet-search but, it didn't worked.
following is my code (without including react-leaflet search). Can anyone help me with it.
import React from "react";
import L from "leaflet";
import 'leaflet-timedimension/dist/leaflet.timedimension.src';
import omnivore from '#mapbox/leaflet-omnivore';
import { Map, Marker, Popup } from 'react-leaflet';
import { ReactLeafletSearch } from 'react-leaflet-search';
// import * as countries from './data/map.geojson';
const config = {};
config.default = {
center: [51.505,-0.09],
zoomControl: true,
zoom: 4,
maxZoom: 19,
minZoom: 11,
scrollWheel: false,
legends: true,
infoControl: true,
attributionControl: true
};
config.tdOptions = {
timeInterval: "2018-09-30/2018-10-30",
period: "PT1H",
};
// ===== Example data sources
config.wmsOne = {
url: "https://demo.boundlessgeo.com/geoserver/ows",
options: { layers: 'nasa:bluemarble', transparent: true },
attribution: "© <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
};
config.wmsTwo = {
url: "https://demo.boundlessgeo.com/geoserver/ows",
options: { layers: 'ne:ne', transparent: true },
attribution: "© <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
};
config.osmLayer = {
url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
params: {
minZoom: 11,
attribution: "© <a href="http://osm.org/copyright">CHANGE THIS</a> contributors",
id: '',
accessToken: ''
}
};
// ===== END Example data sources
export default class LeafletMap extends React.Component {
constructor() {
super();
this.state = {
lat: config.default.center[0],
lng: config.default.center[1],
zoom: config.default.zoom,
toggleActive: true,
timeInterval: config.tdOptions.timeInterval,
period: config.tdOptions.period,
gpxLayer: null,
gpxTimeLayer: null,
};
this.initMap = this.initMap.bind(this);
this.initTimeDimension = this.initTimeDimension.bind(this);
this.onClick = this.onClick.bind(this); // Necessary?
}
// Executed when component is mounted Leaflet-React MAP component
componentDidMount() {
this.initMap();
// this.initTimeDimension(); // TODO: MAKE WORK GOOD!
}
initMap() {
// Usual Leaflet way, but we're using react-leaflet's <Map> component instead
/*this.map = new L.map("root", {
center: [this.state.lat, this.state.lng],
zoom: config.params.zoom,
timeDimension: true
});*/
console.log("### Initializing Leaflet map");
// Tile layer(s)
const tileLayerA =
L.tileLayer.wms(config.wmsOne.url, config.wmsOne.options);
const tileLayerB =
L.tileLayer.wms(config.wmsTwo.url, config.wmsTwo.options);
const tileLayerC = L.tileLayer.wms(config.osmLayer.url)
.addTo(this.map.leafletElement);
// const countriesLayer = L.geoJson(countries, {});
// Add controls for toggling layers
L.control.layers({
"OSM Layer": tileLayerC,
"Layer Two": tileLayerA,
"Layer One": tileLayerB
}).addTo(this.map.leafletElement);
}
// TODO: Make work!
initTimeDimension() {
console.log("### Init Leaflet TimeDimension");
let gpxTl = L.timeDimension.layer.geoJson(this.state.gpxLayer, {
updateTimeDimension: true,
addlastPoint: true,
waitForReady: true
});
this.setState({gpxLayer: omnivore.gpx('public/running_mallorca.gpx')});
this.setState({gpxTimeLayer: gpxTl});
// TimeDimension layer(s)
const td = new L.timeDimension({
period: "PT5M",
});
this.map.timeDimension = td;
//Player -> Component to animate a map with a TimeDimension, changing the time periodically.
let player = new L.TimeDimension.Player({
transitionTime: 100,
loop: false,
startOver:true
}, td);
L.control.timeDimension({
player: player,
}).addTo(this.map.leafletElement);
// Add timedimension from GPX data
new L.timeDimension.layer.geoJson(this.state.tdData, {
updateTimeDimension: true,
addlastPoint: true,
waitForReady: true
}).addTo(this.map.leafletElement);
}
onClick = () => {
this.setState({
toggleActive: !this.state.toggleActive,
});
console.log('CLICKED MAP');
// this.map.leafletElement.fitBounds(this.state.tdData);
};
render() {
const position = [this.state.lat, this.state.lng];
const timeDimensionOptions = {
timeInterval: this.state.timeInterval,
period: this.state.period
};
return (
<React.StrictMode>
<Map
center={position}
zoom={this.state.zoom}
onClick={this.onClick}
timeDimension={true}
timeDimensionOptions={timeDimensionOptions}
timeDimensionControl={true}
ref={(ref) => { this.map = ref; }}>
{/*<TileLayer
attribution={config.wmsOne.attribution}
url={config.wmsOne.url}
/>*/}
{/*<WMSTileLayer
layers={this.state.toggleActive ? 'nasa:bluemarble' : 'ne:ne'}
url="https://demo.boundlessgeo.com/geoserver/ows" />*/}
<Marker position={position}>
<Popup>
A pretty CSS3 popup (react-leaflet component). <br />Easily customizable.
</Popup>
</Marker>
</Map>
</React.StrictMode>
);
} // END of render()
}
Use this :
import { SearchControl } from 'react-leaflet-search';
It works, although it's not on the Documentation
Can you post a jsfiddle or codepen demonstrating the problem?
Also... incidentally the way you are adding controls and layers to the map is not recommended by react-leaflet.
new L.timeDimension.layer.geoJson(this.state.tdData, {...}).addTo(this.map.leafletElement);
is imperative. Prefer declarative rendering like
import { Map, TileLayer, GeoJSON } from 'react-leaflet';
<Map>
<TileLayer>
<GeoJSON>
</Map>