Search code examples
javascriptreactjsrefreact-dom

Access to a several elements through one ref React


I wanna get access to multiple elements with using refs feature. Then after I could iterate through elements of this.tabs. Code below doesn't work, how fix it to make work? Solution, which I use now is document.querySelectorAll('tabs'), but it doesn't seems right for React.

class Comp extends React.Component {
  constructor(props) {
    super(props);
    
    this.tabs = React.createRef();
  }
  
  componentDidMount() {
    console.log(this.tabs);
  }


  render() {
    return (
      <div>
        <span class="tab" ref={this.tabs}>One</span>
        <span class="tab" ref={this.tabs}>Two</span>
        <span class="tab" ref={this.tabs}>Three</span>
      </div>
    );
  }
}

ReactDOM.render(
  <Comp />,
  document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


Solution

  • You're assigning refs incorrect way. Do it in the early beginning of render() method:

    this.tabs = []
    

    refs are going to be assigned via

    <span className="tab" ref={(tab) => { this.tabs.push(tab) }}>One</span>
    

    I hope you could call this.tabs this case!