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
As Nick Parsons has suggested:
Creating an object with refs:
the modified code can be:
Yes you can do is using eval() in JS.
Edit: Using eval() seems not a good approach here.Using window[] is the simplest one can do.
Then use the ref like this: