I am trying to catch an element using an ID in React, but I could not.
render() {
  //Looping through all menus
  let menuOptions = this.props.menuLists.map(menuList => {
    return (
      <li className="nav-item active" key={menuList.name}>
        <a className="nav-link" href={menuList.anchorLink}>
          {menuList.name}
        </a>
      </li>
    );
  });
  return (
    <React.Fragment>
      <div id="animSec">
        <canvas id="myCanvas" />
      </div>
    </React.Fragment>
  );
}
I want to call the myCanvas ID.
I tried by this.refs, but it's sent me undefined. I also tried react-dom:
ReactDOM.findDOMNode(this.refs.myCanvas);
but get nothing. I call findDOMNode on the constructor first and I tried componentDidMount but get nothing.
You can use Callback Refs to retrieve the ID:
class YourComponent extends React.Component {
  constructor(props) {
    super(props)
    this.canvas = null
  }
  componentDidMount() {
    console.log(this.canvas.id) // gives you "myCanvas"
  }
  render() {
    return (
      <React.Fragment>
        <div id="animSec">
          <canvas id="myCanvas" ref={c => {this.canvas = c}}></canvas>
        </div>
      </React.Fragment>
    )
  }
}
alternatively, for React v16.3+, you can use createRef():
constructor(props) {
    super(props)
    this.canvas = React.createRef()
  }
  componentDidMount() {
    console.log(this.canvas.current.id) // gives you "myCanvas"
  }
  render() {
    return (
      <React.Fragment>
        <div id="animSec">
          <canvas id="myCanvas" ref={this.canvas}></canvas>
        </div>
      </React.Fragment>
    )
  }
If you set up a ref in your constructor as this.canvasRef = React.createRef() and apply it to your canvas as
<React.Fragment> 
  <div id="animSec">
    <canvas ref={this.canvasRef}></canvas>
  </div>
</React.Fragment>
You should be able to access the element directly. You can console log or check your dev tools to view the ref value. And (to my best knowledge), it's best practice to use Refs compared to querySelectors in React. You might also check out this post to see if you can work around with a method on canvas.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With