Sunday, May 5, 2019

React Tooltip Component published in NPM

Tooltip could be create with pure CSS, that's the example:
Such an awesome tooltip!

https://jsfiddle.net/AndrewBuntsev/jxk75o6c/

But I decided to go further and create a react component and publish it at NPM so that it could be reusable it other applications. That's the component HOC function implementation:
  1. import React from "react";
  2. import "./Tooltip.css";
  3. export function tooltip(InnerComponent, options) {
  4. return class extends React.Component {
  5. render() {
  6. return (
  7. <div className="react-fancy-components-tooltip-container">
  8. <span className="tooltiptext" style={options.style}>
  9. {options.text}
  10. </span>
  11. {InnerComponent}
  12. </div>
  13. );
  14. }
  15. };
  16. }
import React from "react";
import "./Tooltip.css";

export function tooltip(InnerComponent, options) {
  return class extends React.Component {
    render() {
      return (
        <div className="react-fancy-components-tooltip-container">
          <span className="tooltiptext" style={options.style}>
            {options.text}
          </span>
          {InnerComponent}
        </div>
      );
    }
  };
}

That's how we can use the tooltip function in another component:
  1. import { tooltip } from "./components/tooltip/Tooltip";
  2. function App() {
  3. let TooltippedComponent = tooltip(<input />, {
  4. text: "Awesome tooltip!!",
  5. style: {
  6. fontWeight: "bold"
  7. }
  8. });
  9. return (
  10. <div className="App">
  11. <TooltippedComponent />
  12. </div>
  13. );
  14. }
import { tooltip } from "./components/tooltip/Tooltip";

function App() {
  let TooltippedComponent = tooltip(<input />, {
    text: "Awesome tooltip!!",
    style: {
      fontWeight: "bold"
    }
  });
  return (
    <div className="App">
      <TooltippedComponent />
    </div>
  );
}

If you you need a guide how to publish react components to NPM, follow this https://github.com/AndrewBuntsev/react-component-publish
Or if you just need this component you can install it from NPM https://www.npmjs.com/package/react-fancy-components
Its code on github https://github.com/AndrewBuntsev/react-fancy-components

No comments:

Post a Comment