React file submission does not trigger input onChange event

In my React project, I have created an input component that should trigger a custom handleSubmit function when a user uploads a file:

function PhotoInput({ enableInput }) {
    const inputStyle = {
        display: 'none'
    };

    const handleSubmit = (event) => {
        console.log("Uploading file...")
        // putToS3Bucket(event.target.files[0], '/upload')
    };

    if (enableInput) {
        console.log("logged")
        return (
            <input
                id="file-input"
                type="file"
                style={inputStyle}
                accept="image/*"
                onChange={handleSubmit}
            />
        );
    } else {
        return null;
    }
}

function PhotoPopover({ width, open, handlePhotoClickClose, enableInput, anchorRef }) {
    const navigate = useNavigate();
    

    return (
        <>
            <MenuPopover
                open={open}
                onClose={handlePhotoClickClose}
                anchorEl={anchorRef.current}
                sx={{ width: { width } }}
            >
                <label for="file-input">
                    <MenuItem
                        onClick={handlePhotoClickClose}
                        sx={{ typography: 'body2', py: 1, px: 2.5 }}
                    >
                        <Iconify
                            icon='eva:settings-2-fill'
                            sx={{
                                mr: 2,
                                width: 24,
                                height: 24
                            }}
                        />
                        Change Profile Photo
                    </MenuItem>
                </label>
                <PhotoInput enableInput={enableInput} />
            </MenuPopover>
        </>
    );
}

Despite setting everything up correctly, the handleSubmit function does not get triggered when selecting a file to upload from the file dialogue after clicking on the MenuItem. It's puzzling because it works fine in a sandbox example, but not in this code snippet. Any insights into what might be causing this discrepancy would be greatly appreciated.

Answer №1

When working with React, it's important to note that an input type="file" is considered as an uncontrolled component. To access information about the uploaded files, utilize the File API. For more details, refer to The file input Tag.

function PhotoInput({ enableInput }) {
  const fileInput = useRef(); /* create a ref*/
  const inputStyle = {
    display: 'none',
  };

  const handleSubmit = () => {
    event.preventDefault();
    /* grab current files using ref */
    console.log('Uploading file...', fileInput.current.files[0].name);
  };

  if (enableInput) {
    return (
      <input
        id="file-input"
        type="file"
        style={inputStyle}
        ref={fileInput} /* add ref*/
        accept="image/*"
        onChange={handleSubmit}
      />
    );
  } else {
    return null;
  }
}

Check out the working example here

Answer №2

To improve the function call, consider updating the format like so:

onChange={(event) => handleSubmit(event)}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring FileReader in conjunction with React and Typescript

I am facing an issue while trying to upload a JSON file using an input element of type file. When I attempt to use the onload method on FileReader in TypeScript, I receive an error message saying "Cannot invoke an object which is possibly 'null'. ...

A guide to connecting keyboard events to div elements within a React application

Currently working on a basic react project to gain some practical experience with the library. I aim to develop a simple user interface with blank spaces to be filled in by typing via keyboard input. Here's a glimpse of my progress so far: function ...

Using the fetch function in React can lead to a variety of outcomes - from unauthorized errors to

I'm struggling with an issue and I'm hoping for some assistance. Currently, I am trying to execute a simple fetch request before the DOM is fully rendered. However, I have encountered a problem where sometimes I receive a 401 error because the ...

Encountering an Invalid Host header while connecting a domain name with a reactjs application

Currently, I am in the process of deploying a JS application (with the backend in nodejs and front-end in reactjs) on a hosting server. To ensure smooth operation, I have dockerized all components including the back end, front end, and database. As of now, ...

Menu Styled <ul> Not Activating handlerOut

My navigation menu is structured using an unordered list (<ul>) with customized styling (see markup & CSS below) <ul id="TopNavigation"> <li><a href="#" id="products" class="products">PRODUCTS</a></li> ...

Is there a solution to resolving the error "FirebaseError: Firebase: Error (auth/invalid-api-key)" in a NextJS + Firebase application?

https://i.sstatic.net/cX8dZ.png While working on integrating Firebase into my NextJS app, I ran into an issue. Let me provide some context to help you understand the situation better. In my project, I have a .env file where all the necessary Firebase conf ...

What steps can be taken to troubleshoot and resolve the API problem causing a 400 error in a react

I'm currently working on my react project and attempting to add a new page. I've set up all the models, controllers, and routes, but unfortunately, the data from the form on my newly added page isn't being posted into the MongoDB collection. ...

Creating an HTML return statement to specifically target and extract a certain string while disregarding additional data

Looking for a solution to trim a long string returned by a webpage, while ensuring essential data is not removed. Counting characters is not feasible due to the varying length of the return. The return format is as follows: GET /New%20Messenger&subti ...

Incorporate a background image with the JavaScript CSS property

I'm having trouble adding a background image using the Javascript CSS property in my code. When I directly add the 'url', it works fine. Could the issue be with the 'weatherImage' variable? Javascript var OpenWeatherKey = ' ...

Having trouble with React's useEffect and React-Query's useQuery?

As a React newbie, I'm trying to implement global error handling using a context provider and a custom hook. Main Objective: Implementing a system to handle errors at the global level. The Issue: Errors reappear immediately after being removed. I s ...

Guide to correctly selecting <i> tags within a <p> tag using jQuery

I'm attempting to retrieve the text from the i (italic) elements within a paragraph using this code: $('p').each(function(j, element){ if($(element).is("i")){ console.log("The value is: "+$(element).text()); } }); However, ...

Utilizing React Router V4: Implementing a modal that can be displayed on the same screen by only altering the URL, and subsequently using that URL to completely regenerate the screen content

I am currently working on creating a modal that functions similarly to the one used for displaying individual tweets. https://i.sstatic.net/VMLEs.png When the modal is open, a status code is added to the original url in the screenshot. Despite this, I r ...

Issue with Ant-design Modal not closing when a prop is passed to control its behavior

In a separate component, I have a Modal called TestModal set up like this: <Modal title="title" centered={true} visible={this.props.isOpen} okText="Close" onOk={this.props.onClose} > Test </Modal> Th ...

What is the reason behind Material UI's restriction on using camelCase props with "withStyles"?

Struggling with prop casing while diving into the new Material UI (version 1.0.0-beta.33 at the time of writing), I've encountered inconsistencies with withStyles allowing camelCased props in some scenarios but not others. For instance: <ChipInpu ...

CodeIgniter functionality for generating auto-incrementing IDs that are accessible in both the view and within JavaScript's Window.Print() method

While working on creating an invoice, I encountered a few issues. First, I want the Invoice No: to be displayed in my view (receipt.php) as 0001 and use it as the primary key in my tbl_payment table. However, I'm unsure how to have an auto-incremented ...

Utilizing React to Style Background Positions

I've been struggling to position a block of rendered jsx on the right side of the first block for hours now. Despite trying various options like marginTop, marginLeft, and even backgroundPosition based on my research, I still haven't been success ...

Ways to conceal text links on mobile devices using Bootstrap 4

Is there a way to hide the text of a link on mobile screens using Bootstrap 4? How can this be achieved? HTML <li> <a href="#"><i class="fa fa-icon"></i> Text Link</a> </li> I want to show only the icon on mobile de ...

The value in the textarea will stay unchanged even after the form has been submitted

I recently resolved my previous issue, but now I am seeking advice on how to prevent a textarea from clearing its input after submitting a form. You can view the jsFiddle here: http://jsfiddle.net/rz4pnumy/ Should I modify the HTML form? <form id="for ...

Adjust the heights of certain headers in an HTML table, not all of them

Here is the link to my JSBin: https://jsbin.com/xofaco/edit?html,css,output I am facing an issue with an HTML table that has both nested headers and regular headers. My goal is to make all headers equal in height, specifically I want columns labeled "four ...

When I delete the initial element from the array, the thumbnail image disappears

Using react-dropzone, I am attempting to implement image drag and drop functionality. The dropped image is stored in the React state within a files array. However, a problem arises when removing an image from the array causing the thumbnails of the remain ...