skip to Main Content

I have a react component A that is used to upload files, basically when rendered this component receives a file and uploads it, it also displays the file name and upload progress.

I would like to display the file name and progress also in a different part of the page.
If I try rendering the component A in different parts of the page it will upload the file twice.

How can I render A and then clone it’s DOM to another part of the page?
I don’t want to move A logic to parent component

2

Answers


  1. If you want to display the file name and upload progress in a different part of the page without duplicating the file upload logic, you can use React’s Context API or state management libraries like Redux.

    An example using React Context:

    import React, { createContext, useContext, useState } from 'react';
    
    const FileUploadContext = createContext();
    
    const FileUploadProvider = ({ children }) => {
      const [file, setFile] = useState(null);
      const [progress, setProgress] = useState(0);
    
      const uploadFile = async () => {
        // Your file upload logic here
        // Update progress as needed
        // You can use setProgress to update the progress in the context
      };
    
      return (
        <FileUploadContext.Provider value={{ file, progress, uploadFile }}>
          {children}
        </FileUploadContext.Provider>
      );
    };
    
    const FileUploader = () => {
      const { file, progress, uploadFile } = useContext(FileUploadContext);
    
      return (
        <div>
          {/* Your file upload UI and logic here */}
          {file && <p>File: {file.name}</p>}
          {progress > 0 && <p>Progress: {progress}%</p>}
        </div>
      );
    };
    
    const AnotherComponent = () => {
      const { file, progress } = useContext(FileUploadContext);
    
      return (
        <div>
          {/* Display file name and progress in a different part of the page */}
          {file && <p>File: {file.name}</p>}
          {progress > 0 && <p>Progress: {progress}%</p>}
        </div>
      );
    };
    
    const App = () => {
      return (
        <FileUploadProvider>
          <FileUploader />
          {/* Render FileUploader wherever needed */}
          <AnotherComponent />
          {/* Render AnotherComponent wherever needed */}
        </FileUploadProvider>
      );
    };
    
    export default App;
    
    Login or Signup to reply.
  2. This can be done using very easily using React Context, or even with the useState hook. With context you can achieve your goal of not moving logic to a parent component per say, but logic will be added in the form of a context provider.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search