0

I want to access all classes what will be rendered with map() function. I have the next situation:

{arr.map((i, k) => {
return <div ref={car} className={`car-nr-${i.id}`} key={k}}> </div>
})}

Now i tried to access my ref.

const floor = useRef(null) car.current.style.transform =rotateY(10deg); But this does not work.The styles are applying only for last element from my arr. How to access all elements an to apply rotateusing useRef?

Asking
  • 3,487
  • 11
  • 51
  • 106
  • not sure what you are trying to do. it's not clear. however you are assigning the ref only to the last component in the list. (there is only one ref in use for all of the mapped components) – Tom Slutsky Apr 18 '20 at 11:53
  • @TomSlutsky, my question is how to access all elements which will rendered in map() function? I want to apply styles for a all, not only for the last. – Asking Apr 18 '20 at 11:57
  • @TomSlutsky, or i can use querrySelectorAll? – Asking Apr 18 '20 at 11:59
  • I dont see why you need refs here. you can apply styles right in the map function – Tom Slutsky Apr 18 '20 at 12:14
  • Yes as Tom says, you don't need to use refs. You can apply style to the component using the `style` prop. Refs will just make things more complicated than they need to be. – JMadelaine Apr 18 '20 at 12:31
  • @TomSlutsky, i need refs because i want to change style depending by some variables – Asking Apr 18 '20 at 13:05
  • can you provide a more complete example on codesandbox and share it? – Tom Slutsky Apr 18 '20 at 13:07

2 Answers2

1

ref also accepts a callback function which you could use to store all of your refs inside an array:

// Init the array
myRefs = [];

// A new div has been created, add it to the elements array
addRef = (element) => {
    this.myRefs.push(element);
}

// Call your function inside the div
return <div ref={addRef }...
HermitCrab
  • 3,194
  • 1
  • 11
  • 10
0

I think you should create a unique ref for every component. Check an example from here add refs dynamically.

Abdelrhman Arnos
  • 1,404
  • 3
  • 11
  • 22