P
P
persovt2021-06-16 13:23:16
React
persovt, 2021-06-16 13:23:16

How to track the position of a React element?

Who can tell me how to track the position of an element or get many elements at once in ref React (for example, as in querySelectorAll in js)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrew Ghostuhin, 2021-06-22
@Torin_Asakura

paints all elements of the list red

import { useRef, useEffect } from "react";

const Item = ({ element, pushNode }) => {
  const node = useRef(null);

  useEffect(() => {
    pushNode(node);
  }, [node]);

  return <li ref={node}>{element}</li>;
};

const List = ({ elements, pushNode }) => {
  return (
    <ul>
      {elements.map((element) => (
        <Item element={element} pushNode={pushNode} />
      ))}
    </ul>
  );
};

const App = () => {
  const elements = ["one", "two", "three"];
  const nodes = [];

  const pushNode = (node) => nodes.push(node);

  const paintRed = (event) => {
    nodes.forEach((node) => {
      node.current.style.color = "red";
    });
  };

  return (
    <>
      <List elements={elements} pushNode={pushNode} />
      <button onClick={paintRed}>Paint it red</button>
    </>
  );
};

export default App;

elements - just an array of strings that are like elements
nodes - (future) array of refs
pushNode - a callback that pushes to an array of refs, its main essence is to keep the code clean and not to shit in the global scope from the
List component - the usual ul that maps elements creating an Item at each iteration
Item - the usual li inside which is the text of the element from elements
Inside the Item, a ref is created on li, after the component is mounted (so that the ref itself appears), a callback is called that pushes the ref to nodes, then when the button is pressed using DOM'a paint li'shki

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question