13

I have following the code example regarding tooltips in Reactstrap:

constructor(props) {
  super(props);
  this.state = {
    tooltipOpen: true
  };
}
.
.
.
render() {
  return (
    <div>
      <p>Somewhere in here is a <a href="#" id="TooltipExample">tooltip</a>.</p>
      <Tooltip 
        placement="right" 
        isOpen={this.state.tooltipOpen} 
        target="TooltipExample" 
        toggle={this.toggle}>
        Hello world!
      </Tooltip>
    </div>
  ) 
}

And I'm getting the following error:

Error: The target 'TooltipExample' could not be identified in the dom, tip: check spelling

Everything works ok if the initial state is tooltipOpen: false. But I would like the tooltip to appear when the user loads the page...

What should I do?

Community
  • 1
  • 1
Poogy
  • 2,597
  • 7
  • 20
  • 35

4 Answers4

16

In constructor, tooltipOpen should be false.

And then, in componentDidMount, switch tooltipOpen from false to true

This is code:

constructor(props) {
  super(props);
  this.state = {
    tooltipOpen: false,
  };
}

componentDidMount() {
  this.setState({
    tooltipOpen: true,
  });
}
Ryker Tyler
  • 161
  • 1
  • 4
9

Since the introduction of React Hooks this error can be avoided using the following approach.

import React, { useRef } from 'react'
import { UncontrolledTooltip } from 'reactstrap'

const ToolTipExample = () => {

    const ref = useRef(null)

    return (
        <div >
            <p ref={ref}>Hello World</p>
            <UncontrolledTooltip target={ref}>
                Tooltip message goes here :D
            </UncontrolledTooltip>
        </div>
    )
}

This will also work with the Tooltip component.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mustafa J
  • 955
  • 8
  • 9
  • I believe this is needed because the tooltip's sibling is not in the DOM yet while the tooltip is being created, so you need to give it a ref which is valid right away. Thanks. – Noumenon Mar 09 '22 at 04:02
1

I also came across the same problem, the issue was the initial value, the initial value must be false if you put true as initial value the popover looking for the target element that could not be rendered yet, so if you want to open popover as component render update the state in componentDidMount hook.

/* initial value must be false */
state = { isPopoverOpen: false };

componentDidMount() {
  this.setState({
    isPopoverOpen: true,
  });
}

Umair Ahmed
  • 8,337
  • 4
  • 29
  • 37
0

Don't know if anyone needs to know this. But I got the same error when I added the id property to a component instead of an HTML element. Obviously fixed it by adding a wrapping element to my component and placing my id there.

Nick Gr
  • 105
  • 10