I'm working on an app using Leaflet (via react-leaflet). Leaflet directly manipulates the DOM. The react-leaflet library doesn't change that, it just gives you React components that you can use to control your Leaflet map in a React-friendly way.
In this app, I want to use custom map markers that are divs containing a few simple elements. The way to do that in Leaflet is to set your marker's icon
property to a DivIcon, in which you can set your custom HTML. You set that inner HTML by setting the DivIcon's html
property to a string containing the HTML. In my case, I want that HTML to be rendered from a React component.
In order to do that, it seems like the correct approach is to use ReactDOMServer.renderToString()
to render the Component that I want inside the map marker into a string, which I would then set as the html
property of the DivIcon:
MyMarker.js:
import React, { Component } from 'react'
import { renderToString } from 'react-dom/server'
import { Marker } from 'react-leaflet'
import { divIcon } from 'leaflet'
import MarkerContents from './MarkerContents'
export class MyMarker extends Component {
render() {
const markerContents = renderToString(<MarkerContents data={this.props.data} />)
const myDivIcon = divIcon({
className: 'my-marker',
html: markerContents
})
return (
<Marker
position={this.props.position}
icon={myDivIcon} />
)
}
}
However, according to the React docs:
This [renderToString] should only be used on the server.
Is this a strict rule, or is it only meant to dissuade people from circumventing ReactDOM's efficient management of the DOM?
I can't think of another (better) way to accomplish what I'm after. Any comments or ideas would be greatly appreciated.
ReactDOMServer.renderToString()
to accomplish that. Definitely a good reminder to be diligent about sanitizing the HTML, though. – Chelsiechelsy"<div data-reactid='.0'>Hello, World.</div>"
to console viarefs
, which is our component, but we needed to hook into the DOM in order to do so. I'd try to find a React dev on Twitter and pose this to them directly, otherwise, why not give it a shot?renderToString()
, that is. – LupitalupoReactDOMServer.renderToString()
and it's been working fine. I haven't noticed any issues so far. – ChelsiechelsyReactDOM.renderToStaticMarkup
facebook.github.io/react/docs/… if you will not be needing the generated HTML to have React's extra DOM attributes etc. – ToreuticsReactDOM.renderToStaticMarkup
is best suited for static elements, and that the extra DOM attributes added byReactDOMServer.renderToString
are useful for React's internal DOM manipulation when re-rendering. Unless I'm mistaken, the best one to use probably depends on whether you anticipate updates occurring on that component in the future. – Chelsiechelsy