Skip to content

How to obtain a component ref in a function component? #240

Open
@kentcb

Description

@kentcb

Hi,

I'm basically trying to figure out the equivalent of the following JS(X):

import { useRef } from 'react';

function MyComponent() {
  const componentRef = useRef(null);

  // Function to handle a button click
  function handleClick() {
    // Access the component using the ref object
    console.log(componentRef.current);
  }

  return (
    <div ref={componentRef}>
      <button onClick={handleClick}>Click me</button>
    </div>
  );
}

That is, I need to obtain a reference to the ReactElement representing the component itself. Note that I am making an assumption that the above JS is actually correct and that componentRef is a reference to the component itself - I haven't actually verified this.

If I do the obvious thing:

FunctionComponent.Of<Props>(
        (fun props ->
            let rootHook = Hooks.useRef<Option<ReactElement>> = None

            let root = // create the root element, passing rootHook to things that need access to the component itself
				
            rootHook.current <- Some root
            root
        )

It doesn't work because I'm capturing a ReactElement rather than the component itself.

If I try to use a dom.div with Props.RefValue, it captures a browser element rather than a ReactElement (let alone the component).

So I'm unclear on how I obtain a reference to the component itself from within the implementation of a function component. In a class-based component, one would simply use this, but I can't use a class-based component.

Thanks

PS. In case you're wondering, my use case is I am trying to get a reference to the component to pass it to a ReactXP Popup as an anchor. The Popup needs to be anchored to the component that displays it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions