I want to access an element using React.createRef() (which is inside a function). Below is the example of how I want to access it.
react:
someFunction = () => {
let element = this.myRef.current;
console.log(element)
}
render(){
return(
<FlexView>
<div ref={this.myRef}>
some text here
</div>
{this.someFunction()}
</FlexView>
)
}
Here, I want to access the div element through someFunction(). But for some reason this.myRef.current is returning a null value in console - I guess the issue is related to react life cycle, but I just can't figure out why. However by using the button, I can able to access the div element without having any problem, but only when I try to use the above method to trigger a function it's returning null.
render(){
return(
<FlexView>
<div ref={this.myRef}>
some text here
</div>
<button onClick={this.someFunction()}>click-here</button>
</FlexView>
)
}
Can someone please let me know how do it.
p.s. I'm new to React and Js
componentDidMountto get the data after comonent rendered likecomponentDidMount() { this.someFunction(); }. Working example here codesandbox.io/s/react-createref-forked-kwdbgd