React - ref returns null in event handler

Asked

Viewed 34 times

0

I’m developing with React at a time but had found no reason to use refs, decides to read the documentation more deeply and I came across several examples that indicate to developers where it would make sense to use them. In the documentation the example used is that of an DOM element, in the case of a button totally génerico but which would make sense to keep a reference.

const FancyButton = React.forwardRef((props, ref) => (
    <button ref={ ref } { ...props }>{ props.children }</button>
));

const ref = React.createRef();

function App(props) {

    function onClick(e) {
        console.log(ref.current);
    }

    return (
        <FancyButton ref={ ref } onClick={ onClick }>Clique aqui!</FancyButton>
    );

}

ReactDOM.render(<App />, document.getElementById("root"))

As a test to verify what was returned from a reference I implemented a click event handler that would simply print the value of ref.Current but only get the value null. Could someone tell me where I’m going wrong?

  • Failed to pass the refs to the fancybutton inside Apps. <FancyButton ref={ref}>Click me!</FancyButton>. In the doc is demonstrated the use of forwardRef.

  • Sorry I forgot to put in the example but in my test the same still does not work.

  • So, I tbm tested just to be sure, it is not common I use createRef, I usually use more useRef, but here occurred the waiting, the element is returned. Follows the Codesandbox

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.