1

refs in list component remains at 10, even when adding another item to prop in parent component. Additional added inputs when clicking the button in the list component do not get a ref assigned.

const App = () => {
  const [items, setItems] = useState(new Array(10).fill({}));
  
  return (
    <div className='App'>
      <ItemList items={items} />
      <button onClick={() => setItems([...items, {}])}>Add item</button>
    </div>
  );
}
const List = ({items}) => {
  const refs = useRef(items.map(i => React.createRef()));
  
  return (
    <div className='List'>
      {items.map(item, i) => (
        <Item ref={refs.current[i]} item={item} key={i} />
      )}
    </div>
  );
}
const Item = React.forwardRef(({item}, ref) => {
  return (
    <div className='Item'>
      <input ref={ref}/>
    </div>
  );
});

1 Answer 1

1

Try to add the new ref using a useEffect hook inside your ItemList component

 useEffect(() => {
    refs.current.push(React.createRef())
 },[items])    
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.