简体   繁体   中英

How to show tooltips for react-select?

I need to show tooltips for react-select container (not for a separate options) using react-tooltip library.

I made my own SelectContainer component based on the original one and added there data-tip and data-for HTML attributes. Tooltip shows up but when I change selected value it disappears and is not displayed any more.

Here is my code:

const getSelectContainer = options => props => {
  return (
    <components.SelectContainer
      {...props}
      innerProps={{
        ...props.innerProps, ...{
          'data-tip': options.tooltipText,
          'data-for': options.tooltipId,
        }
      }}
    />
  )
}

const CustomSelect = (props) => {
  const tooltipId='tooltip_id'
  const tooltipText='tooltip'
  const selectedOption = colourOptions.filter(option => option.value === props.value)
  
  return (
    <div>
      <ReactTooltip effect="solid" html={true} place="bottom" id={tooltipId} />
      <Select
        defaultValue={colourOptions[4]}
        value={selectedOption}
        options={colourOptions}
        classNamePrefix="react-select"
        onChange={item => props.onChange(item.value)}
        className="my-select"
        components={{
          SelectContainer: getSelectContainer({
            tooltipText:tooltipText,
            tooltipId:tooltipId
          })
        }}
      />
    </div>
  )
}

class Page extends Component {
  constructor (props) {
    super(props)
    this.state = {
      selectValue: 'red'
    }
  }
  render () {
    const onChange = (value)=> {
      this.setState({selectValue: value})
      //alert(value)
    }
    return (
      <CustomSelect
        value={this.state.selectValue}
        onChange={onChange}>
      </CustomSelect>
    )
  }
}

See full example here :

If I wrap Select with another <div> and assign tooltip HTML attributes to it everything works correctly but I don't want to add one more DOM element just for that.

What can I do to show tooltips after changing selection?

Try rebuilding the react-tooltip when the state changes.

useEffect(() => {
    ReactTooltip.rebuild();
}, [state]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM