How to make react-native-elements Tooltip size dynamic based on its content?

Viewed 2790

The React Native Elements Tooltip (docs here) requires you to pass in the width and height property for the tooltip, but I want to create a generic tooltip button that can receive any element as its popover prop.

The following example is what I have, but it uses the default size set to the tooltip by the React Native Element library:

import React from 'react'
import { Tooltip } from 'react-native-elements'
import styled from 'styled-components'

const Container = styled.View`
  justify-content: center;
  align-items: center;
  background-color: #aaf;
  height: 25px;
  width: 25px;
  border-radius: 12.5px;
`

const Icon = styled.Text``

export default function TooltipButton({ tooltip }) {
  return (
    <Tooltip popover={tooltip}>
      <Container>
        <Icon>?</Icon>
      </Container>
    </Tooltip>
  )
}

When the content is bigger than the default size it looks like this.

I Don't want to have to pass a fixed size as prop to this component, I would like it to have a tooltip size depending on it's content.

3 Answers

After some time trying to figure this out, I managed to do a somewhat autosize tooltip button that receives a content element as a prop (tooltip) and resizes itself based on its content.

The only way I got it to work properly was to set an initial size bigger than the content (500x500) and add more size to it (+30).

import React, { useState } from 'react'
import { Tooltip } from 'react-native-elements'
import styled from 'styled-components'

const Container = styled.View`
  justify-content: center;
  align-items: center;
  background-color: #aaf;
  height: 25px;
  width: 25px;
  border-radius: 12.5px;
`

const Icon = styled.Text``

export default function TooltipButton({ tooltip }) {
  const [tooltipSize, setTooltipSize] = useState({ w: 500, h: 500 })

  const tooltipClone = React.cloneElement(
    tooltip,
    { onLayout: (e) => setTooltipSize({ w: e.nativeEvent.layout.width, h: e.nativeEvent.layout.height }) }
  )

  return (
    <Tooltip 
      popover={tooltipClone} 
      width={tooltipSize.w + 30} 
      height={tooltipSize.h + 30}
    >
      <Container>
        <Icon>?</Icon>
      </Container>
    </Tooltip>
  )
}

End result looks like this.

I guess it's enough to add 20 units to width and height. That's required because the default style applied to the Tooltip component adds a padding of 10, see here.

It seems that using null forces height and width to take as much space as the contents need!

height={null} // using height={null} seems to look good
width={null} // using width={200} seems to look better than null

Source of this hint: ToolTip in react native

Related