How to add “refs” dynamically with react hooks?

后端 未结 3 1444
粉色の甜心
粉色の甜心 2020-12-08 10:38

So I have an array of data in and I am generating a list of components with that data. I\'d like to have a ref on each generated element to calculate the height. I know how

3条回答
  •  一整个雨季
    2020-12-08 10:55

    I created a tiny npm package that exposes a React Hook to handle setting and getting refs dynamically as I often run into the same problem.

    npm i use-dynamic-refs
    

    Here's a simple example.

    import React, { useEffect } from 'react';
    import useDynamicRefs from 'use-dynamic-refs';
    
    const Example = () =>  {
      const foo = ['random_id_1', 'random_id_2'];
      const [getRef, setRef] =  useDynamicRefs();
    
      useEffect(() => {
        // Get ref for specific ID 
        const id = getRef('random_id_1');
        console.log(id)
      }, [])
    
        return ( 
          <>
            {/* Simple set ref. */}
            
    
             {/*  Set refs dynamically in Array.map() */}
            { foo.map( eachId => (
              
    Hello {eachId}
    ))} ) } export default Example;

提交回复
热议问题