DEV Community

Keertivaas S
Keertivaas S

Posted on

Sending Functions as Props in React

I am sure this concept would be a little too basic for some of you but just wanted to write about it as I faced a real world scenario for this usecase.

At work, I was presented with a challenge. There were 2 screens in the UI (Lets assume mobile UI - The screens were quite small). I was supposed to upload data (assuming images) in both the screens and the submit button in the second screen would submit the entire data (both the images).

Solution :

So, the state for the files would be in a common component. The state and the setter function would be passed as a prop to the respective components.

Since the state is maintained in the common component, there is no loss of data.

Simple code example (just a basic skeleton) :

const UploadComponent = (props) => {
  const { files, setFiles } = props;
  const onFileUploadA = (file) => {
    setFiles([...files, file]); // Appending file
  };
  return (
    <Upload onSubmit={(file) => onFileUploadA(file)} />
  );
};

const CommonComponent = (props) => {
  const [files, setFiles] = useState([]);
  return (
    <>
      <UploadComponent {...props} files={files} setFiles={setFiles} back={false} /> {/* Front page */}
      <UploadComponent {...props} files={files} setFiles={setFiles} back={true} /> {/* Back page */}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

The second upload just appends the new upload to the list of uploads, thus preventing loss of data.

Top comments (0)