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.
For passing the data from the child component to the parent component, we have to create a callback function in the parent component and then pass the callback function to the child component as a prop. This callback function will retrieve the data from the child component.
Scroll to an Element With the React Refs (References): The most simple way is to use ref to store the reference of the element that you want to scroll to. And call myRef. current. scrollIntoView() to scroll it into the view.
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)
}
}
forwardRef is what you need here to implement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With