1

So, I'm trying to implement the react forwardref example for my component, as I want to control a scrollbar inside.

Here's what I have:

const MessagesFC = React.forwardRef((props, ref) => {       
    return <Flex
        className={"Messages"}
        direction={"Column"}
        ref={ref}>
        {messages}
    </Flex>
});

const scrollDivRef = React.createRef<any>();

React.useEffect(() => {
    scrollDivRef.current?.scrollIntoView({ behavior: "smooth"})
}, [ scrollDivRef, chatRoom.messages ])

Inside my return(), the component is added like this:

<MessagesFC 
    ref={scrollDivRef}/>

Seems to be setup just like in the example.

However, when executing this code, the scrollDivRef.current is always undefined.

So, where did I go wrong?

Screenshot of my code:

enter image description here

8
  • Where is useEffect used? May 24, 2020 at 10:19
  • @ShubhamKhatri useEffect is part of the React API.
    – Baruch
    May 24, 2020 at 10:20
  • Obviously I know that, in your post useEffect is written independenly from MessagesFC. This is what creates confusion since hooks cannot be used outside of functional components May 24, 2020 at 10:21
  • @ShubhamKhatri Not my post, and it's not obvious that you know since you're asking where its defined and the answer is in the React API. Anyway, scrollDivRef.current I believe is undefined because the reference only exists inside the forwardRef callback.
    – Baruch
    May 24, 2020 at 10:24
  • It highly depends on how and where you have used defined the MessagesFC functional component. Please add more code that provides this information May 24, 2020 at 10:26

1 Answer 1

5

First of all you must note that in a functional component you must use useRef to define ref and not React.createRef since useRef will return you the same ref instance everytime whereas React.createRef will give you a different ref instance

Second, MessageFC component needs to be defined outside of the Parent component not inside of its body, otherwise a new instance of it is created again and you will always see the component getting remounted which is why the scrollDivRef inside of useEffect will not give you accurate information

Third You don't need to add scrollDivRef as a dependency to useEffect.

const MessagesFC = React.forwardRef((props, ref) => {       
    return <Flex
        className={"Messages"}
        direction={"Column"}
        ref={ref}>
        {messages}
    </Flex>
});

const Parent = () => {
    const scrollDivRef = React.useRef<any>();

    React.useEffect(() => {
        scrollDivRef.current?.scrollIntoView({ behavior: "smooth"})
    }, [ chatRoom.messages ]);

    ...
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.