U
U
uzi_no_uzi2020-07-15 23:47:51
JavaScript
uzi_no_uzi, 2020-07-15 23:47:51

How to pass ref to child element via props?

There is this component:

class Services extends React.Component {

    constructor(props) {
        super(props);

        this.slider = React.createRef();
    }

    render() {

        const sliderOptions = {
            dots: false,
            infinite: true,
            speed: 500,
            slidesToShow: 2,
            slidesToScroll: 1,
            arrows: false,
        }

        return(
            <section className={style.services}>
                <div className={style.servicesLeft}>
                    <Accordion />
                    <SliderArrows slider={this.slider} />
                </div>
                <div className={style.servicesRight}>
                    <Slider ref={this.slider} {...sliderOptions}>
                        <ServiceItem  />
                        <ServiceItem  />
                    </Slider>
                </div>
            </section>
        )
    }

}


I need to pass a reference to the slider (<Slider></Slider>) to the arrow( <SliderArrows />) component via props. The problem is that in the component , the <SliderArrows />passed reference is null, i.e. it is not transmitted. After reading the documentation, I came across forwardRef, but I didn’t fully understand how it works and whether it would even help in my cases

Here is what I tried to do myself:
I created an HOC
import React from 'react';

function ForwardRefSlider(Slider) {
    return React.forwardRef((props, ref) =>{
        <Slider />
    })
}


The ForwardRefSlider function takes the slider component, wraps it in a forwardRef, I don’t know if I’m moving in the right direction or not, then I’m just stuck, how can I use this function further, where my link will be and how to pass it to the <SliderArrows />component is not clear.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
Jasulan98, 2020-07-16
@Jasulan98

I think I would move the function to the parent component and pass the child component to both. But I don't know how right

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question