Reputation: 2641
I have an array of data which contains objects with unique ids.
I am trying to create as many references as neccessary. For example, if the array have 4 elements then I will create 4 references. Each reference has to be contained in an array and also, I need to associate it to the unique id of the object.
Here is what I am trying to do in "pseudocode":
data = [{id: "10i3298yfrcd", ...}, {id: "y48hfeucldnjs", ...}]
references = data.map(({id}) => useRef(null))
I don't know how to associate each created reference to its respective object id (just to access the references like with an array of alphanumeric indexes, or something like this)...
Also, I get an error when creating the references this way:
React has detected a change in the order of Hooks called by %s. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/docs/hooks-rules.html
So I suppose this is not a valid form to create references dynamically.
Any ideas how to do that? Thank you.
Upvotes: 0
Views: 908
Reputation: 555
this is how you can create a useRef depending of data.lenght
import { useEffect, useRef, useState } from react;
const ArrayInputs = () => {
const inputRef = useRef([]);
const [data, setData] = useState([]);
useEffect( () => {
let data = ['Name', 'Age', 'Gender'];
inputRef.current = new Array(data.length);
setData(data);
}, []);
useEffect( () => {
//Example of using inputRef
if(data.length !== 0) {
inputRef.current[data.length - 1].focus();
}
}, [data]);
return(
<View>
{data.map( (element, i) => <TextInput ref = {el => inputRef.current[i] = el} />)}
</View>
);
}
Upvotes: 6