kyrylolv
kyrylolv

Reputation: 320

onChange event fires on wrong mapped file input element

I am stuck on this issue with onChange handler being fired on a wrong element after .map function. I have a component, which I use to display mapped values, which looks like this:

const Step: React.FC<StepProps> = ({ status, title, text, onClick, onChange }) => {
  return (
    <button disabled={status === CompletionStatus.Completed} className={Styles.item} onClick={onClick}>
      <mui.IconButton css={css.completionIcon} disabled={status === CompletionStatus.Completed}>
        {status === CompletionStatus.Completed ? <muiIcons.Check /> : <Plus />}
      </mui.IconButton>

      <div className={Styles.content}>
        <span className={status === CompletionStatus.Completed ? Styles.titleCompleted : Styles.title}>{title}</span>

        <span className={status === CompletionStatus.Completed ? Styles.textCompleted : Styles.text}>{text}</span>
      </div>

      {onChange && (
        <>
          <label htmlFor="file-button" className={Styles.inputLabel} />
          <input id="file-button" className={Styles.input} type={'file'} onChange={onChange} />
        </>
      )}
    </button>
  );
};

So, some of the mapped elements are being used with onClick, and two use onChange to gain photos from the user.

The issue is, that every time I trigger the onChange event on any of those inputs, only the first ones fires, e.g (I added this onChange function to test the name of the element that is being fired, and every time only the first one in the list is being console.logged)

onChange={(event: any)=> {
  console.log(event, step);
  event.target.value = null;
}}

Upvotes: 1

Views: 267

Answers (2)

kyrylolv
kyrylolv

Reputation: 320

So, I have figured out the issue here, maybe someone finds this helpful. Having input with type file only having one id (file-button) was causing only the first such input to work

<label htmlFor="file-button" className={Styles.inputLabel} />
<input id="file-button" className={Styles.input} type={'file'} onChange={onChange} />

The way I fixed this, was basically having that id property unique, so I passed an index to the component and changed the id to

id={`file-button-${index}`}

Upvotes: 1

John Detlefs
John Detlefs

Reputation: 1037

Sounds like you may not have set a key for each item in your mapping function.

{yourData.map((item, index) => <Component key={`item-${index}`} item={item} />)}

Upvotes: 0

Related Questions