Ken
Ken

Reputation: 1471

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.

Upvotes: 0

Views: 1005

Answers (3)

Akhil Aravind
Akhil Aravind

Reputation: 6130

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>
    )
  }
}

Upvotes: 1

Subin Sebastian
Subin Sebastian

Reputation: 10997

You are console logging in the constructor before Dom is actually rendered. Try console logging in an onClick handler instead.

export default class SomeClass extends Component {
 constructor(props) {
  super(props);
  this.intro = React.createRef();
 }
 print = () => {
   console.log(this.intro.textContent);
 }
 render() {
   return (
     <div>
       <div ref={this.intro}>Hi</div>
       <button onClick={this.print}>Print</div>
     </div>
   )
 }

}

Upvotes: 1

Anas M.I
Anas M.I

Reputation: 582

Its because you are logging it in constructor. Run the code in componentDidMount lifecyle.

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

  }


componentDidMount(){
      console.log(this.intro.textContent);
    }

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

Upvotes: 1

Related Questions