Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

array of refs react

import React, { useRef, useEffect } from 'react';
import ReactDOM from 'react-dom';

const words = ['Many', 'Words'];

const App = () => {
  const wordsRef = useRef([]);

  const displayWords = words.map((word, i) => (
    <React.Fragment key={i}>
      <span ref={el => (wordsRef.current = [...wordsRef.current, el])}>
        {word}
      </span>
    </React.Fragment>
  ));

  useEffect(() => {
    console.log(wordsRef);
    console.log(wordsRef.current[0].classList);
  });

  return <div>{displayWords}</div>;
};

ReactDOM.render(<App />, document.getElementById('root'));
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #array #refs #react
ADD COMMENT
Topic
Name
6+7 =