Poogy
Poogy

Reputation: 2767

Reactstrap tooltip causes an error: The target 'TooltipExample' could not be identified in the dom

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?

Upvotes: 15

Views: 16089

Answers (4)

Nick Gr
Nick Gr

Reputation: 157

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.

Upvotes: 1

Mustafa J
Mustafa J

Reputation: 1055

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.

Upvotes: 10

Umair Ahmed
Umair Ahmed

Reputation: 8787

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,
  });
}

Upvotes: 1

Ryker Tyler
Ryker Tyler

Reputation: 158

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,
  });
}

Upvotes: 16

Related Questions