Keyur Golani
Keyur Golani

Reputation: 583

Is there any way to define a custom attribute in react similar to angular?

Consider the usecase. I want to have a tooltip functionality in my react application. The way I want to set it up is when I write <input type="text" tooltip="Enter your name here">, this should apply tooltip saying "Enter your name here" on the textbox. This should be applicable to any eligible element in my app. So that whenever I need to apply a tooltip on any element, I just need to write tooltip="..." attribute on it.

I am familiar that in AngularJS you might go about it something like this.

angular.module('app')
.directive('tooltip', function() {
  return {
    restrict: 'A',
    link: function($scope, $el) {
       // Apply Tooltip through JS or applying right CSS class
    }
  }
}

But I am not sure if there's something similar available in React. Or may be if it needs to be constructed, how should I approach creating something like this.

Upvotes: 0

Views: 103

Answers (2)

Estus Flask
Estus Flask

Reputation: 222493

The question is basically whether React has the concept of directives. And the answer is no.

React offers components that are supposed to be composed. As opposed to Angular components, React components don't necessarily create DOM elements, so nested components won't put restrictions on the layout.

So tooltip should be defined as a component:

class Tooltip extends React.Component {
  render() {
    const child = React.Children.only(this.props.children);

    return React.cloneElement(
      child,
      { className: classNames(child.props.className, 'tooltip') }
    );
  }

  componentDidMount() {
    const childElement = ReactDOM.findDOMNode(this).children[0];
    const tooltipText = this.props.title;
    // init a tooltip
  }

  componentWillUnmount() {
    // clean up a tooltip
  }
}

And used like:

<Tooltip title="foo"><Foo/></Tooltip>

Upvotes: 1

Daniel Khoroshko
Daniel Khoroshko

Reputation: 2721

This it could be something like that.. though I wouldn't recommend fiddling with DOM really.

class TooltipProvider extends React.Component {
  componentDidMount() {
    document.querySelectorAll('[tooltip]').forEach(el => {
       // set up a tooltip
    });
  }

  componentDidUpdate() {
    document.querySelectorAll('[tooltip]').forEach(el => {
       // set up a tooltip
    });
  }


  render() {
    return children;
  }

}

// somwhere in your app

return () {
   <TooltipProvider>
      // The rest of the app
   </TooltipProvider>
}

Upvotes: 0

Related Questions