2

So I'm mapping array of objects in jsx to create categories which are sections on my page. It looks like this

{categories.map(category => (
        <div className="single-category" key={category.id}>
          content of single category
        </div>
      ))}

My goal is to get array of refs.current of every single category, so I can pass it to my other component which is category navbar, where thanks to offsetTop I can compare it with window.offsetY and give corresponding category in navbar active class in CSS. I think this is possible with refs but I don't know how to do it correctly. Can anyone help? I appreciate any help :)

Filippo854
  • 149
  • 9
  • Do you want to set a special class when is a category on screen? – Milos N. Jan 20 '21 at 20:50
  • Does this answer your question? [How can I use multiple refs for an array of elements with hooks?](https://stackoverflow.com/questions/54633690/how-can-i-use-multiple-refs-for-an-array-of-elements-with-hooks) – Matias Kinnunen Jan 20 '21 at 21:04
  • Not in 100%, I get the array I want, but on first render my array is empty @mtsknn , Yes I want e.g to give border bottom to category in navbar that is corresponding to section of this category on screen – Filippo854 Jan 20 '21 at 21:16
  • @Filippo854 Can you show us what you have tried and what you are trying to do (i.e. also show the code where you are setting border-bottom etc.)? It would make it easier to locate the problem(s). – Matias Kinnunen Jan 21 '21 at 06:31

1 Answers1

0

if you are in a functional component just declare a new variable containing a reference and assign the dom element you want to refer to with exemple : ref={myRef}

const myRef = React.useRef(null)




  return (
     {categories.map(category => (
    <div className="single-category" key={category.id} ref={myRef} >
      content of single category
    </div>
  ))}
)

then you can pass myRef.current to the component you want and if you are in a class component use React.createRef instead of useRef

Moukim hfaiedh
  • 409
  • 6
  • 9