Notorious776
Notorious776

Reputation: 493

React wrapper component not working as expected

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?


Upvotes: 0

Views: 932

Answers (1)

Zhang TianYu
Zhang TianYu

Reputation: 1195

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.

Upvotes: 1

Related Questions