Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to convert a string to a reference variable name in react?

I have a reference variable:

const weightInputRef = useRef();
const weightInputRef = useRef();

I have some data:

const inputs = [{
    ref: heightInputRef,
    type:'number',
    placeholder: 'Height',
    name: 'height'
  },
  {
    ref: weightInputRef,
    type:'number',
    placeholder: 'Weight',
    name: 'weight'
  }]

I am using it to setup connection between the following HTML elements:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{inputs.map((item, index) => <Input
  name={inputs[index].name}
  placeholder={inputs[index].placeholder}
  type={inputs[index].type}
  inputRef={inputs[index].ref}
/>
)}

Will it be possible to send the variable name directly instead? Like:

ref=item.name+"InputRef"

I think it can save a lot of code. Is there any way I can achieve that?

Here is my Input component:

export default function Input(props) {
  return (
    <input
      className={classes.input} 
      placeholder={props.placeholder} 
      type={props.type} 
      ref={props.inputRef}
      name={props.name}
    />
  )
}

>Solution :

Yes you can do is using eval() in JS.

ref=eval(item.name+"InputRef")

Then use the ref like this:

   export default function Input(props) {
  return (
    <input
      className={classes.input} 
      placeholder={props.placeholder} 
      type={props.type} 
      ref={eval(item.name+"InputRef")}
      name={props.name}
    />
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading