React - accessing ref from "unrelated" component

201 Views Asked by At

I have a React App with this sort of structure:

const App = () => {
    return (
        <AnimatedBackground/>        
        <HomePage/>
    )
}
    
const AnimatedBackground = () => {
    return (
        <canvas>
            // consume ref here v
            <BackgroundParticles/>
        </canvas>        
    )
}

const HomePage = () => {
    return (
        <div>
            <SearchBar/>  // <- reference this component
            <OtherStuff/>
        </div>
    )
}

Until now SearchBar and BackgroundParticles were completely independent from each other, but I have decided to make the animated BackgroundParticles interact with (bounce off) SearchBar, for which I need the latter's measures and coordinates (ref.current?.getBoundingClientRect()).

Since the common parent (App) is several levels up, what is the proper way of accessing a reference to SearchBar from BackgroundParticles? Do I have to use forwardRef at all from App or do I drill the ref down to SearchBar as a regular prop? How would I consume the SearchBar ref from BackgroundParticles in the other branch? With a context.provider from App?

Cheers =)

0

There are 0 best solutions below