I am still confused if I use useRef([]);
the right way, as itemsRef
returns Object {current: Array[0]}
. Here in action: https://codesandbox.io/s/zealous-platform-95qim?file=/src/App.js:0-1157
import React, { useRef } from "react";
import "./styles.css";
export default function App() {
const items = [
{
id: "asdf2",
city: "Berlin",
condition: [
{
id: "AF8Qgpj",
weather: "Sun",
activity: "Outside"
}
]
},
{
id: "zfsfj",
city: "London",
condition: [
{
id: "zR8Qgpj",
weather: "Rain",
activity: "Inside"
}
]
}
];
const itemsRef = useRef([]);
// Object {current: Array[0]}
// Why? Isn't it supposed to be filled with my refs (condition.id)
console.log(itemsRef);
return (
<>
{items.map(cities => (
<div key={cities.id}>
<b>{cities.city}</b>
<br />
{cities.condition.map(condition => (
<div
key={condition.id}
ref={el => (itemsRef.current[condition.id] = el)}
>
Weather: {condition.weather}
<br />
Activity: {condition.activity}
</div>
))}
<br />
<br />
</div>
))}
</>
);
}
In the original example I receive // Object {current: Array[3]}
when I console.log(itemsRef);
The difference is that I used in my version itemsRef.current[condition.id]
as its a nested map loop and therefore i
doesn't work.
import React, { useRef } from "react";
import "./styles.css";
export default function App() {
const items = ["sun", "flower", "house"];
const itemsRef = useRef([]);
// Object {current: Array[3]}
console.log(itemsRef);
return items.map((item, i) => (
<div key={i} ref={el => (itemsRef.current[i] = el)}>
{item}
</div>
));
}