0

Introduction

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":

Pseudocode

 data = [{id: "10i3298yfrcd", ...}, {id: "y48hfeucldnjs", ...}]

 references = data.map(({id}) => useRef(null))

Problem

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.

1
  • Problem here is that React Hooks can only be called at the top level in functional components. You are calling useRef hook inside a callback function which is not allowed. You should visit the link in your question to read more about the rules of using hooks. Commented Sep 14, 2020 at 11:52

1 Answer 1

6

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>
    
    );

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.