skip to Main Content

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:

{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}
    />
  )
}

2

Answers


  1. Chosen as BEST ANSWER

    As Nick Parsons has suggested:

    Creating an object with refs:

    const refsObject = {
      weight: weightInputRefs,
      height: heightInputRefs
    }
    

    the modified code can be:

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

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

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

    Edit: Using eval() seems not a good approach here.Using window[] is the simplest one can do.

    Then use the ref like this:

       export default function Input(props) {
      return (
        <input
          className={classes.input} 
          placeholder={props.placeholder} 
          type={props.type} 
          ref={window[item.name+"InputRef"]}
          name={props.name}
        />
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search