Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 602
Ramazan Chasygov Avatar asked May 09 '18 12:05

Ramazan Chasygov


People also ask

How do you get multiple elements in React?

Use a React fragment to return multiple elements from a component, e.g. <><div>First</div><div>Second</div></> . React Fragments are used when we need to group a list of children without adding extra nodes to the DOM. Copied! We used a React fragment to group a list of children without adding extra nodes to the DOM.

Can we use two ref IN React?

If you've used React, you'll be familiar with ref. It is easier to use, but you would need multiple refs to be attached to the component for certain use cases. In that situation, you might probably use a library.

Can you pass ref to component?

Ref forwarding is a technique for automatically passing a ref through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries.


1 Answers

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!

like image 53
asiniy Avatar answered Sep 22 '22 13:09

asiniy