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>
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.
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.
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.
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!
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