0

How to create ref and access the ref in es7.

class SomeComponent extends Component {
  state = {
    count: 0,
    this.myRef = React.createRef() //error
    myRef: React.createRef(), // Unused state field: 'myRef'  
  }

  render() {
    return <div ref={this.myRef} />; //error  
           <div ref={myRef} /> // error 'myRef' is not defined
    }
 }

1 Answer 1

1

Create the ref in the constructor like this:

class SomeComponent extends Component {
  constructor(props) {
    super(props);

    this.myRef = React.createRef();
  }

  render() {
    return <div ref={this.myRef} />;
    }
 }

Here is the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.