简体   繁体   中英

How do I use React refs in a map for functional components?

I have a map function which renders a list of divs and these divs are based on the components state, so it is dynamic. I need to put a ref on each of these items on the list so that the user can basically press up and press down and traverse the list starting from the top.

Something like this:

const func = () => {
 const item = items.map((i, index) => {
    return (
      <div ref={index}>{i.name}</div>
    )
  });
}

This has been difficult since it seems like refs are not like state where they can change based on dynamic data. Its initialized once and set to a constant. But I don't know what to initialize it as until this list is rendered and I can't call the useRef hook in a function of course so what is the solution here?

EDIT:

Ok so, its seems there needs to be some more context around this question:

I have a dropdown which also allows the user to search to filter out the list of items. I want to make an enhancement to it so that when the user searches it focuses on the first element and allows the use of arrow keys to traverse the list of elements.

I got stuck when I tried to focus on the first element because the first element doesn't exist until the list is rendered. This list changes dynamically based on what the user types in. So how do you focus on the first element of the list if the list is always changing as the user types?

This can be done without refs, so it should probably be done without refs.

You can put the index of the currently focused element into state. Whenever the displayed data changes, reset the index to 0:

const [focusedElementIndex, setFocusedElementIndex] = useState(0);
useEffect(() => {
  setFocusedElementIndex(0);
}, [items]);
// using this approach,
// make sure items only gets a new reference when the length changes

When rendering, if you need to know the focused index to change element style, for example, just compare the index against the state value:

<div class={index === focusedElementIndex ? 'focused' : ''}

And have a keydown listener that increments or decrements focusedElementIndex when the appropriate key is pressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM