Tylerlee12 Tylerlee12 - 28 days ago 22
Javascript Question

How to get DOM element within React component?

I'm rendering multiple of the same component, each with their own tooltip. Can I write code that will only look within the HTML of each component, so I'm not affecting all the other tooltips with the same class name? I'm using stateless components. Here is the code:

OptionsComponent.js:

import React from 'react';

const OptionsComponent = () => {
const toggleTooltip = event => {
document.getElementsByClassName('listings-table-options-tooltip').classList.toggle('tooltip-hide');
event.stopPropagation();
};
return (
<div className="inline-block">
<span onClick={toggleTooltip} className="icon icon-options listings-table-options-icon"> </span>
<div className="tooltip listings-table-options-tooltip">
Tooltip content
</div>
</div>
);
};


Backbone.js has something like this, allowing you to scope your document query to begin within the view element (analogous to a React component).

Answer

With React, you don't want to modify the DOM. You just re-render your component with new state whenever something happens. In your case, since you want the OptionsComponent to track its own tooltip state, it really isn't even stateless. It is stateful, so make it a component.

It would look something like this:

class OptionsComponent extends React.Component {
  state = {
      hide: false
  };

  toggleTooltip = (ev) => this.setState({ hide: !this.state.hide });

  render() {
      const ttShowHide = this.state.hide ? "tooltip-hide" : "";
      const ttClass = `tooltip listings-table-options-tooltip ${ttShowHide}`;
      return (
        <div className="inline-block">
            <span onClick={this.toggleTooltip} className="icon icon-options listings-table-options-icon"> </span>
            <div className={ttClass}>
                Tooltip content
            </div>
        </div>
      );

      // Alternatively, instead of toggling the tooltip show/hide, just don't render it!
      return (
        <div className="inline-block">
            <span onClick={this.toggleTooltip} className="icon icon-options listings-table-options-icon"> </span>
            {/* do not render the tooltip if hide is true */}
            {!this.state.hide && 
                <div className="tooltip listings-table-options-tooltip">
                    Tooltip content
                </div>
            }
        </div>
      );
  }
}