0

I am writing a button component in React.js that allows the user to upload as many files as they want to the app. My problem is, I can only upload one file at a time with the following code:

  const handleClick = event => {
    setViewPath(['My Files']);
    hiddenFileInput.current.click();
  };
  // Call a function (passed as a prop from the parent component)
  // to handle the user-selected file
  const handleChange = event => {
    const fileUploaded = event.target.files[2];
    props.handleFile(fileUploaded);
  };
  return (
    <>
      <Button className={classes.uploadButton}
      onClick={handleClick}>
        +Upload File(s)
      </Button>
      <input
        type="file"
        ref={hiddenFileInput}
        onChange={handleChange}
        style={{display: 'none'}}
      />
    </>
  );

So the function "const handleChange" is what's responsible for uploading the actual file itself. Any ideas on how to make it so that it can upload as many files as the user pleases?

1 Answer 1

0

You need to add multiple attribute to your input field.

<input type="file" id="files" name="files" multiple>

Your files state should be an array and handleChange should be something like this.

const handleChange = e => {    
setData({
        ...data,
        files: [...data.files, ...e.target.files],
      });
    }
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.