Search code examples
reactjsreact-ref

Implementation of react-intersection-observer module not working on multiple components


I am struggling with the implementation of the "react-intersection-observer" and i can't for the life of me find a solution.

Details:

I have a simple presentation site which i wanna do with React so i can also learn. Right now the website has only the homepage and the homepage has so far these sections: header, about, portfolio and contact form.

What i wanna do is to simply add a class on each section (about, portfolio and contact form) once the section is in viewport. The kind of stuff that with jquery would be over in 2 minutes.

I have installed "react-intersection-observer" and so far the code in my homepage.component.jsx looks like this:

import React from 'react';
import Header from "../../components/header/header.component";
import About from "../../components/about/about.component";
import PortfolioList from "../../components/portfolio-list/portfolio-list.component";
import ContactForm from "../../components/contact-form/contact-form.component";
import { useInView } from 'react-intersection-observer';

const HomePage = () => {
    const { ref, inView, entry } = useInView({
        /* Optional options */
        triggerOnce: true,
        threshold: 1,
        onChange: (inView, entry) => {
            console.log("salam");
            console.log(inView);
            console.log(entry);
            if (inView) {
                entry.target.classList.add("in-view");
            }
        }
    });

    return (
        <div>
            <Header/>
            <main className="main">
                <About />
                <PortfolioList />
                <ContactForm />
            </main>
        </div>
    );
};


export default HomePage;

When i have added ref={ref} on each component like this:

<About ref={ref} />
<PortfolioList ref={ref} />
<ContactForm ref={ref} />

i have received an error: Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?

The thing is that i don't want to add the useInView module in each of the 3 jsx components because it seems bad practice to have repeat code.


Solution

  • Passing ref as props is bad practice.

    Use React.forwardRef instead:

    https://beta.reactjs.org/apis/react/forwardRef

    Check this example:

    https://beta.reactjs.org/apis/react/forwardRef#forwarding-a-ref-through-multiple-components