I'm trying to use refs created from an array but when I check in the Component tab of the React Developper Tools, ref passed to the input are always undefined. Something I missed here?
const MyComponent = () => {
const refs = useMemo(() => Array(2).fill(0).map(i => React.createRef()), []);
const TextInput = ({ name, value, inputRef }) => (
<input
name={name}
value={value}
onChange={updateField()}
ref={inputRef}
/>
)
return (
<TextInput
name="lastname"
value="Nom *"
inputRef={refs[0]}
/>
<TextInput
name="firstname"
label="Prénom *"
inputRef={refs[1]}
/>
)
}
Thanks!
If you have a variable number of refs, you'll want a function-style ref instead, like below.
const TextInput = ({
name,
value,
refs
}) => (
<input
name={name}
value={value}
ref={(el) => {
refs.current[name] = el;
}}
/>
);
const MyComponent = () => {
const refs = React.useRef({});
React.useLayoutEffect(() => {
console.log(refs.current);
}, []);
return (
<>
<TextInput name="lastname" value="Nom *" refs={refs} />
<TextInput name="firstname" value="Prénom *" refs={refs} />
</>
);
};
This will log
{lastname: HTMLInputElement, firstname: HTMLInputElement}
As an aside: never nest components – that will cause unnecessary rerenders.