Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
React refs created from Array not working

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!

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!