What's the equivalent of document.querySelectorAll('.classname')
in React? I understand I should use Refs, but how dow I observe multiple Refs onScroll
?
I usually use a function like the one below to check the viewport position of multiple elements in the page, and trigger different css animation when each element enters the viewport:
HTML
<ul>
<li data-position="below-viewport"></li>
<li data-position="below-viewport"></li>
<li data-position="below-viewport"></li>
<li data-position="below-viewport"></li>
</ul>
Javascript
getPosition: function (element) {
const rect = element.getBoundingClientRect();
if ((rect.top > -1) && (rect.top < (window.innerHeight * 0.75))) {
element.setAttribute('data-js-position','in-viewport');
} else if ((rect.top > 0) && (rect.top < window.innerHeight)) {
element.setAttribute('data-js-position','entering-viewport');
} else if (rect.top > window.innerHeight) {
element.setAttribute('data-js-position','below-viewport');
} else if (rect.bottom < 0) {
element.setAttribute('data-js-position','above-viewport');
}
}
window.addEventListener('scroll', function() {
[].forEach.call(document.querySelectorAll('[data-js-position]'), el => {
positionChecker.getPosition(el);
})
});
How would I implement something similar in React? Can you give me an example of a function that observes multiple divs in React?
Even better: how can I abstract this function in App.js
, so that I can use it also in child Components?
The equivalent of the document. querySelector() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .
It's still possible to use querySelector in React, however, React encourages developers not to use it. Instead, we should aim to use refs if possible.
querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The querySelectorAll() method in HTML is used to return a collection of an element's child elements that match a specified CSS selector(s), as a static NodeList object. The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers.
Make each li
html element its own component and hold a ref
reference to it in its own state.
class LiElement extends React.Component {
componentDidMount() {
this.ref.getPosition()
}
render() {
return (
<li ref={(ctx) => this.ref = ctx}>
</li>
)
}
}
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