5

We have a react project that uses styled components, with a ThemeProvider providing a theme object that all of the components should be able to reference. In this project, we have a leaflet map, and we're adding React components to it in the form of markers, using ReactDOMServer.renderToString. When it tries to to access theme in the component's styles, theme is undefined. Adding the component in a normal way, it works properly.

I'm able to force it to work by manually importing the theme object into the map component, and passing the theme object to the marker component as a property, but that seems a bit hacky - it would be better to find out why the context is getting lost.

In the map component:

const nodeContents = (
    <NodeIcon_svg />
    );
const nodeIcon = Leaflet.divIcon({html: ReactDOMServer.renderToString(nodeContents),
    iconSize: [60, 60],
    iconAnchor: [30, 30]
});

Leaflet.marker(latLng, { icon: nodeIcon }).addTo(_mapLayer);

In the NodeIcon component's styles (theme contains an object with several named colors):

export const NodeIcon_svg = styled.svg`
    polygon {
        stroke: ${({ theme }) => theme.colors.blue1)};
        fill: transparent;
    }
`;

If I add this to the map component:

import themeColors from '../../theme';

And add this line to where we add the NodeIcon:

theme={themeColors}

It works. But it's kind of a hack - it should be able to use the theme.

What should happen (and is what happens when the NodeIcon component is used elsewhere): It finds a color in theme.colors and applies it to the polygon's stroke.

What does happen is the page dies dies with a js error at the line in the style where it attempts to access theme.colors.blue1, saying that it can't be read because the object is undefined. Somehow theme is not making it in to the component, possibly because of using ReactDOMServer.renderToString. Any idea how to make theme available to the marker component without an enormous restructuring of the code (since we already have a working, but awkward, solution)?

0