Home > Blockchain >  How to define conditions based on the length of the files with React.js?
How to define conditions based on the length of the files with React.js?

Time:06-19

What is the best way to define the conditions by file length with react.js for this case?

Here is a sample codesand box

The way I want to do is not only to show just files but also empty boxes based on the length of the file.

If there are no uploaded files which means the default, user will see three empty boxes.

If user uploads one file, user will see one image and two empty boxes.

If user uploads two files, user will see two images and one empty box.

And I removed some codes for this, but if user uploads a third image, user will see a plus icon to add new three empty boxes to upload three images again.

I would like to define the conditions like

If the file length is 1,4,7,10 ...

If the file length is 2,5,8,11 ...

If the file length is 3,6,9,12 ...

The current codes are checking the file length statically.

        {files && (files.length === 2 || files.length === 5) && (
        <div className="app2">
          <div style={{ margin: " auto 0" }}>2</div>
          {files.map((file) => (
            <div className="contianer" onClick={handleClick}>
              <img src={file.url} alt="image1" className="image" />
            </div>
          ))}
          <div className="contianer" onClick={handleClick}></div>
        </div>
      )}

This is the sample that works well.

Change files length to see previews and empty boxes

CodePudding user response:

Try something tike this:

function FilesUploadSheet({ columns, files }) {
  const [rows, setRows] = useState(Math.ceil(files.length / columns));
  const totalSlots = rows * columns;
  const emptySlots = totalSlots - files.length;

  const addRow = useCallback(() => {
    setRows(currentRows => currentRows  );
  }, []);

  return <div>
    {
      files.map(file => (
        <FileBlock file={file} key={file.name} />
      ))
    }
    {
      emptySlots
        ? repeatTimes(emptySlots, index => (
          <EmptyBlock key={index} />
        ))
        : <PlusButton onClick={addRow} />
    }
  </div>
}

function repeatTimes(times, callback) {
  return Array.from({ length: times }, (_, index) => callback(index));
}
  • Related