Home > Enterprise >  How to trigger a function after elements get rendered?
How to trigger a function after elements get rendered?

Time:11-18

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

CodePudding user response:

  class Component extends React.Component{
      constructor(...args){
        super(args);
        this.ref = React.createRef();
      }
      state = {
        isLoaded = false;
      }
      componentDidMount(){
          this.setState({isLoaded:true})     
        }
      someFunction = () => {
         let element = this.myRef.current;
         console.log(element)
      }
      render(){
        <FlexView>
          <div ref={this.ref}>
            some text here 
          </div>
          <button onClick={this.someFunction}>click-here</button>
       </FlexView>
      }
        
    }

CodePudding user response:

My guess is that in the first case the function is expected to return some html i.e div and since the function does not return anything it returns null and nothing is executed inside the render.

  • Related