Created
May 13, 2022 05:33
-
-
Save Phryxia/a4766dc52b926dfac951ddef43e207f9 to your computer and use it in GitHub Desktop.
React component for interactive input for file which can determine to open dialogue or not.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { DetailedHTMLProps, InputHTMLAttributes, MouseEvent, useRef } from 'react' | |
interface Props extends DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement> { | |
isApprovedInitial?: boolean | |
onBeforeFileSelection(): Promise<boolean> | |
} | |
export default function InteractiveFileInput({ isApprovedInitial, onBeforeFileSelection, ...rest }: Props) { | |
const dom = useRef<HTMLInputElement>(null) | |
const isApproved = useRef<boolean>(isApprovedInitial ?? false) | |
async function handleClick(e: MouseEvent<HTMLInputElement>) { | |
if (isApproved.current) return | |
e.preventDefault() | |
isApproved.current = await onBeforeFileSelection() | |
if (isApproved.current) { | |
dom.current?.click() | |
} | |
} | |
return <input ref={dom} onClick={handleClick} {...rest} /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example
Sometimes it's hard to decide within a single callback for file selector. You may need to ask user for the agreement, or you may want to peek an api call to decide it. In this case, you can do this with promise chain.