I have two ponents 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.
I have two ponents 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.
Share Improve this question asked Aug 21, 2018 at 4:09 Nikolai WisenovNikolai Wisenov 1632 gold badges2 silver badges6 bronze badges2 Answers
Reset to default 8React 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.
- First, set the ref in your BannerComponent ponent.
- Second, forward the ref in your App ponent.
- Third, get the forwarded ref in your CarouselComponent ponent.
Alternatively, if you still want to use dom, then I can think of possible way to do like this:
Inside App ponent:
state = {
domMounted: false //initial state
}
ponentDidMount() {
this.setState({domMounted: true})
}
This will ensure your full App ponent is mounted, now you can access the dom element inside your child ponent:
First, pass the props like didMount={this.state.domMounted}
<CarouselComponent didMount={this.state.domMounted}>
CarouselComponent ponent:
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.