简体   繁体   中英

How to get an element By ID inside React.Fragment?

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

You can try using document.getElementById('myCanvas') in a custom function or any life cycle method to target the desired element.
Note that this doesn't work if you're doing SSR with a framework like next.js because there is no document object in the server.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM