Search code examples
javascriptreactjstooltip

React Tooltip using Components


I have a google maps widget on my page with markers on it to represent specific locations. I have made it so that when you click on the marker, a tooltip will appear above it to show more information. I am using react tooltip. Here's my index.jsx

<GoogleMaps
  bootstrapURLKeys={{ key: /* KEY */ }}
  center={center}
  zoom={zoom}
>
  <ReactTooltip
    id="google"
    html
    multiline
  />
  {markers.map((marker) => (
    <Marker
      key={marker.key}
      place={marker}
      lat={marker.lat}
      lng={marker.lng}
    />
  ))}
</GoogleMaps>

Here's my Marker.jsx

import React from 'react';
import MarkerWindow from "./MarkerWindow"

const Marker = ({ place }) => {
  const tip =
    <>
      <MarkerWindow place={place}/>
    </>;
  return (
    <>
      <Wrapper
        data-for="google"
        data-event="click focus"
        data-tip={tip}
      />
    </>
  )
};

export default Marker;

And then my MarkerWindow.jsx

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';

const MarkerWindow = ({ place }) =>
  (
    <StyledSection>
      <h3>${place.name}</h3>
      <p>
        ${place.address}
        <br />
        ${place.number}
        <br />
      </p>
    </StyledSection>
  );

const StyledSection = styled.div`
  width: 18px;
  height: 18px;
  background-color: #e01414;
`;

MarkerWindow.propTypes = {
  place: PropTypes.object.isRequired,
};

export default MarkerWindow;

But when I load the page, I get this:

enter image description here

How do I load custom components into ReactTooltip?


Solution

  • react-tooltip doesn't support components as the tooltip content, but accepts html strings.

    1. You should use the data-html={true} prop to let the react-tooltip know that the value passed to data-tip is actually an HTML code.

    2. Then you should provide the html of the tooltip content as a string.

    So this should work:

    const Marker = ({ place }) => {
      const tip = `
        <div style="width: 18px; height: 18px; background-color: '#e01414';" >
          <h3>${place.name}</h3>
          <p>
            ${place.address}
            <br />
            ${place.number}
            <br />
          </p>
        </div>
      `;
    
      return (
        <>
          <Wrapper
            data-for="google"
            data-event="click focus"
            data-html={true}
            data-tip={tip}
          />
        </>
      )
    };
    
    

    I converted your MarkerWindow component to an HTML string by inlining the styles from the styled-component.

    However, if you are not limmited to use react-tooltip I suggest to use other packages that let you render react components for a tooltip content. Take a look at @tippyjs/react for example.