0

I'm trying to create a HOC which adds a tooltip (later can be more reusable). I've come up with a few working solutions using other methods, but I'd like to make it as simple as possible to use.

Basically, I want to know if there is anyway to force my <Div /> component to render its children without adding {props.children} to the <Div />. If that's possible somehow, then I could really make this better in the future.

import { nest } from 'recompose';

const Tooltip = () => <div style={{ position: 'absolute', top: 0, left: 0, height: '20px', width: '20px', backgroundColor: 'red' }} />;

const Div = (props) => {
  console.log(props);
  return (
    <div
      style={{
        backgroundColor: '#F2F2F2',
        height: '400px',
      }}
    >
      <h1>content here</h1>
    </div>
  );
};

const DivWithTooltip = nest(Div, Tooltip);
germainelol
  • 3,231
  • 15
  • 46
  • 82
  • Why do you not want to write `{props.children}`? You want to render the children, you have to explicit write it. – Isaddo Jun 16 '17 at 05:52
  • @Isaddo Well, I'd like to create some kind of helper which just adds some hover effect to the component such as adding a tooltip. I can do it cleanly by wrapping the component in a `` component but I'm just trying to see if it's possible using a clean HOC. That way I can just say `Component = withHover(Component, TooltipComponent)` or something like that. – germainelol Jun 16 '17 at 06:08

1 Answers1

1

Do you mean something like this? You can use span wrapper instead of div to minimize possible styling problems, generally there is no problem. Use wrapper or props.children, you have to choose one.

const withToolTip = ToolTip => Component => props => (
  <div className="tooltip">
    <Component {...props} />
    <ToolTip {...props} />
  </div>
)

const Div = props => (
  <div>Hover over me</div>
)
const Tip = props => (
  <div className="tooltiptext">tip</div>
)
const DivWithTooltip = withToolTip(Tip)(Div)

ReactDOM.render(
  <DivWithTooltip />,
  document.getElementById('app')
)
.tooltip .tooltiptext {
    visibility: hidden;
}
.tooltip:hover .tooltiptext {
    visibility: visible;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>
Isaddo
  • 438
  • 4
  • 10
  • I thought about doing something like this indeed, but wasn't sure if having the extra `div` as a wrapper would cause any issues with the styling – germainelol Jun 17 '17 at 08:51