0

i like to develop a simple tooltip component in react.js

the tooltip gets defined like so in e.g. App.jsx:

<TooltipLink>Hover over me
    <Tooltip>I am the Tooltip content</Tooltip>
</TooltipLink>

My question is: What is the best way of TooltipLink and Tooltip to talk to each other?

They are nested but I cannot use props because they are not nested directly in the component itself. Also, I don't want to use the parent (e.g. App.jsx) to manage the communication between TooltipLink and Tooltip because I want them to be self-contained.

I thought about refs but when i define a ref inside the Tooltip component then TooltipLink does not know about it (I assume because refs only work when components are nested inside the components themselves).

I could of course use simple DOM-programming for TooltipLink and Tooltip to communicate (e.g. use e.target when the user hovers over TooltipLink and then find its first child) but I thought there must be a more react-y way...

5
  • Are you using something like Redux or MobX? Commented Feb 23, 2018 at 10:57
  • You can use TooltipLink's props.children to communicate with Tooltip (using React.children api : reactjs.org/docs/react-api.html#reactchildren) Commented Feb 23, 2018 at 11:02
  • @chris: nope i want the plugin to be independent from sth like that Commented Feb 23, 2018 at 11:29
  • @dyo: yes but then i only get the unrendered version of the Tooltip (not the actual DOM-element) Commented Feb 23, 2018 at 11:29
  • @nerdess You use can pass "callback" functions as props to the children to do the communication like you do in a simple parent/child communication, maybe this can help you understand : javascriptstuff.com/component-communication Commented Feb 23, 2018 at 11:33

1 Answer 1

0

You have 3 options:

  • cascading props in the whole hierarchy
  • using redux
  • using the context API

I prefer to use redux, because the context API is not officially supported (breaking changes may happen, like in react 16.3). Cascading props is not really beautiful but may be convenient for small apps. (<MyComponent {...props}>)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.