Skip to content

Throw error on invalid id #620

@gforge

Description

@gforge

Issue description

  • components: utils
  • reactstrap version #5.0.0-alpha.3
  • import method es
  • react version #16.0.0
  • bootstrap version #4.0.0-beta

What is happening?

The getTarget() fails when an ID contains spaces

What should be happening?

I would like the getTarget() to check and throw an error if the string is incorrect, alternatively use getElementById() that is space safe.

Steps to reproduce issue

From the tooltip example:

import React from 'react';
import { Tooltip } from 'reactstrap';

export default class Example extends React.Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      tooltipOpen: false
    };
  }

  toggle() {
    this.setState({
      tooltipOpen: !this.state.tooltipOpen
    });
  }

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

Error message in console

TypeError: this._target is null

Code

Here's a suggested fix:

export function getTarget(target) {
  if (isFunction(target)) {
    return target();
  }

  if (typeof target === 'string' && document) {
    let selection = document.querySelector(target);
    if (selection === null) {
      select = document.querySelector(`#${target}`);
      if (selection === null) {
        select = document.getElementById(target);
        if (selection === null) {
          throw new Error(`The target '{target}' could not be identified in the dom, tip: check spelling`);
        }
      }
    }
    return selection;
  }

  return target;
}

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions