0

I have the following code

const inputRef = useRef<HTMLInputElement>(null);

const handleClick = () => {
  if (inputRef.current) inputRef.current.click();
};

return (
    <Container fixed>
      <div className={classes.root}>
        <Grid container spacing={1}>
          {data &&
            data.map(category => (
    ...
    <Link to={`/products/${category.id}`}>
    ...
<input
  accept="image/*"
  hidden
  type="file"
  ref={inputRef}
  onChange={e => handleChange(e, category.id)}
/>
<IconButton onClick={handleClick}>
  <InsertPhoto />
</IconButton>

For some reason, the Link component category.id is 1 but in handle change, I simply console log the id and it returns 10 (the last category.id) how is this possible? the full code can be found here https://pastebin.com/ZiDTkdTU

1 Answers1

1

The problem with your code is ref you're using.

You have several categories (you mentioned 10) in data array. But there is only one inputRef exists. So when iterating over array you bind this single ref to every input. At the end inputRef is bound to last <input> element.

Then you click <IconButton> to insert photo and this click is transferred to <input> element, which opens file selection dialog (as it has type="file"). But whatever <IconButton> click is always transferred to last <input> element as you have single inputRef. So onChange is also fired for last input always, showing you id === 10.

The problem is becomes worse as <input> elements are hidden and you don't see what <input> element accept file.

The solution is to create array of refs, each for single <input>.

Here is sample to showcase this effect. Whatever 'Select file' button you choose, file will be selected for last <input> and console will always log 3.

Here is correct sample which uses ref array.

Fyodor Yemelyanenko
  • 11,264
  • 1
  • 30
  • 38
  • Could you show me some example of creating an array of refs? as far as I know this is not possible –  Jul 01 '19 at 07:13
  • You may look at https://stackoverflow.com/questions/47055464/how-to-assign-refs-to-multiple-components. This describes how to use array of refs – Fyodor Yemelyanenko Jul 01 '19 at 07:46