8

I have two components CarouselComponent and BannerComponent nested to App Component. I would liked to get the element in BannerComponent in CarouselComponent for scrolling function.

Code is here;

--- App.js

....
<App>
   <BannerComponent />
   <CarouselComponent />
</App>
....

--- BannerComponent.js

...
return(
<div className="banner-div" id="banner-div">
</div>
);
...

--- CarouselComponent.js

...
scrollTo() {
  document.getElementById("banner-div") //  This doesn't work
}
...

return(
<a onClick={this.scrollTo}></a>
); 

I wanna know how to get element in react js in all situations.

2 Answers 2

8

React ref will work here.

class SomeComp extends React.Component{

constructor(){
    this.carRef = React.createRef(); //create ref
}
  render(){
    return(
      <div>
        <App>
          <BannerComponent  carRef={this.carRef}/> //pass ref in Banner Component to attach it to required DOM.
          <CarouselComponent carRef={this.carRef}/> //pass ref to CarouselComponent  to use it
        </App>
      </div>
    )
  }
}

BannerComponent

class BannerComponent extends React.Component{

  render(){
    return(
      <div className="banner-div" id="banner-div"  ref={this.props.carRef}>
      </div>
    );
  }   
}

CarouselComponent

class CarouselComponent extends React.Component{

  scrollTo() {
    this.props.carRef.current.scrollTo(50)
  }

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

1 Comment

Thank you very much for your kind help. It works now.
4

forwardRef is what you need here to implement.

  • First, set the ref in your BannerComponent component.
  • Second, forward the ref in your App component.
  • Third, get the forwarded ref in your CarouselComponent component.

Alternatively, if you still want to use dom, then I can think of possible way to do like this:

Inside App component:

state = {
  domMounted: false //initial state
}

componentDidMount() {
  this.setState({domMounted: true})
}

This will ensure your full App component is mounted, now you can access the dom element inside your child component:

First, pass the props like didMount={this.state.domMounted}

<CarouselComponent didMount={this.state.domMounted}>

CarouselComponent component:

const {didMount} = this.props
if(didMount) { // this will run on every render and finally get true
  document.getElementById("banner-div")
}

Now, your onClick handler will not get null element and the event will work fine.

Comments

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.