简体   繁体   中英

File upload button is making whole component clickable

I'm trying to build a simple file upload input for a form in React. I'd like to have a custom button that a user presses in order to trigger the file upload input. It seems the way to do this is to attach a useRef to the input and then use the click event to trigger the file input. All this works except when I do this it makes the entire component clickable. All the searches I've done yield the opposite answer, which is explaining how to make the whole component clickable. I don't want that behavior and I can't figure out why it is doing this.

const fileInputField = useRef(null);

const handleClick = () => {
    fileInputField.current.click();
  };

    
<div className="file-upload-box">
                
                <p>Drag a file here or</p>

                <button onClick={handleClick}>
                  BROWSE
                </button>
    
           
                <input
                  style={{ display: "none" }}
                  type="file"
                  title=""
                  value=""
                  ref={fileInputField}
                  
                />
</div>

In javascript, any event is triggered bubbling to its parents until reaching the root element.

You need to stop event propagation from the button.

const handleClick = (e) => {
    e.stopPropagation();
    fileInputField.current.click();
};

Or if you can check in the component click event if the target element of the event is the BROWSE button to return click function and not execute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM