javascriptreactjsref

How to set react ref in a for loop


I have a 'fileUpload' component which I am passing into a form in my React App.

I want to have the ability to set a unique ref for each input element in my for loop and then pass this ref to a delete button to remove the file.

FileUploadComponent

const FileUpload = ({ addFile, runClick }) => {
          const uploadButton = [];
          const myRefs = React.useRef([]);
        
          for (let i = 1; i < 6; i += 1) {
            uploadButton.push(
              <div key={i}>
                <input
                  type="file"
                  id={`file${i}`}
                  ref={myRefs.current[i] ?? React.createRef()}
                  name={`file${i}`}
                  onChange={addFile}
                />
                <RemoveButton type="button" onClick={() => removeFile()}>
                  X button{i}
                </RemoveButton>
              </div>
            );
          }
    
      return uploadButton;
    };
    
    export default FileUpload;

FormComponent

//working without using the FileUploadComponent and setting/passing the ref manually

<InputField className="col">
        <input
          type="file"
          id="file3"
          name="file3"
          ref={ref3}
          onChange={addFile}
        />
        <RemoveButton type="button" onClick={() => removeFile(ref3)}>
          X
        </RemoveButton>
      </InputField>

// trying to have the ref be automatically assigned and passed to delete button

<InputField className="col">
    <FileUpload addFile={addFile} runClick={() => removeFile()} />
  </InputField>

Solution

  • You can create an array of refs before the loop, using Array.fill():

    const myRefs = useRef(new Array(6).fill(createRef()));
    

    And use it in the loop like:

    <input type="file" ref={myRefs[i]}/>