0

I am using React-Dropzone and following the first example on the website:

function MyDropzone() {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      Hello
    </div>
  );
}

I want to create a wrapper class like this:

function MyDropzone() {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });

  function Wrapper({ children }) {
    return (
      <div {...getRootProps()}>
        <input {...getInputProps()} />
        {children}
      </div>
    );
  }

  return <Wrapper>Hello</Wrapper>;
}

but when I do this, react-dropzone stops working. When I click the element, nothing happens whereas on the first example it works fine. Isn't this how wrapper components work or am I missing something?


Notorious776
  • 453
  • 6
  • 19

1 Answers1

1

You can do it like this.

function Wrapper({ children }) {
  const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop });
  return (
    <div {...getRootProps()}>
      <input {...getInputProps()} />
      {children}
    </div>
  );
}

function MyDropzone() {
  return <Wrapper>Hello</Wrapper>;
}

The reason behind this is if you define Wrapper inside MyDropzone functional component, it will define new component everytime you render. Which means if will rerendered every render.

Zhang TianYu
  • 1,163
  • 5
  • 11
  • One issue I have with this is I want to use the useDropzone hook in both the Wrapper component and the MyDropzone component. Initializing it in both makes it stop working. Any suggestions on how to overcome this? – Notorious776 Jun 06 '21 at 14:00