0

I have a class component in React with a ref and I want to access it within a functional component inside of it. I tried passing the ref as a prop, but then it says that it's undefined. So then I tried accessing it with this.refs but it's undefined too.

function GetOffset() {
  const [offset, setOffset] = useState(0);
  useEffect(() => {
    function handleScroll() {
      
    console.log(this.refs);
      
  }, [offset]);
}

I want to use getBoundingClientRect() to check an offset of an element but first I need to access the ref from inside this component.

I read that using a class component would work, but I need the useEffect() hook. Any tips?

0

1 Answer 1

1

useRef

const MyFunctionalComponent = () => {
   const ref = useRef();
   const [offset, setOffset] = useState(0);
   useEffect(() => {
      // access ref.current
   },[offset]);
   
   return <MyClassComponent ref={ref}/>
}


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

1 Comment

I can't thank you enough!!! I tried useRef before but it looks like I was doing it wrong

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.