Search code examples
reactjsref

React ref undefined


so I'm having a little trouble using ref's with React.

All I'm trying to do is print the text content of an element using ref's like this:

export default class SomeClass extends Component {
  constructor(props) {
    super(props);
    this.intro = React.createRef();
    console.log(this.intro.textContent);
  }

  render() {
    return (
      <div ref={this.intro}>Hi</div>
    )
  }
}

However, this always prints null or undefined instead of "Hi" which is what I want.


Solution

  • You should use current with ref, like this.ref.current.textContent

    Check the stackblitz demo Here

    export default class App extends Component {
      constructor(props) {
        super(props);
        this.intro = React.createRef();
      }
    
     componentDidMount(){
          console.log( this.intro.current.textContent);
        }
    
     render() {
        return (
          <div ref={this.intro}>Hi</div>
        )
      }
    }