Home > Software engineering >  Ref react dynamically
Ref react dynamically

Time:10-17

Suppose I've some useRef:

const mango = useRef();
const grape = useRef();
const potato = useRef();

And some data:

{
    mango: 'yellow',
    grape: 'purple',
    potato: 'pc'
}

I iterate over the data and due to my data keys are same as useRef const so I want to assign the value of data to useRef, like:

key.current.value = data[i]

But because of key.current.value in reality isn't a useRef, it'll not work. useState may work but I need a useRef solution since I've to get and set the value of input fields using useRef.

CodePudding user response:

If I'm interpreting you right here...

Remember that refs on elements can also be functions. That is, you can do

function Component() {
  const inputRefs = React.useRef({});
  return (
    <div>
      <input ref={i => inputRefs.current.foo = i} />
      <input ref={i => inputRefs.current.bar = i} />
      <input ref={i => inputRefs.current.quux = i} />
    </div>
  );
}

to populate the inputRefs object with references to those HTML elements (or null as they're getting unmounted).

CodePudding user response:

You can create an object to use as a lookup for them based on a string either by creating them in an object

const myRefs = { 
  'mango': useRef(); // Change 'mango' to whatever you want to lookup this ref as later
  'grape': useRef();
  'potato': useRef();
}

Then look them up with something like:

const data = { 
    mango: 'yellow',
    grape: 'purple',
    potato: 'pc'
}

const keys = Object.keys(data);
keys.forEach( key => { 
  myRefs[key].current.value = data[key] // key is mango, grape, potato and matches data in both objects
})

Or whatever/however else you want to modify or look them up.

  • Related