react#DragEvent TypeScript Examples
The following examples show how to use
react#DragEvent.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.ts From webapis-playground with MIT License | 6 votes |
function onDrag(event: DragEvent) {
const target = event.target as HTMLElement;
event.dataTransfer.setData('text', target.id);
if (target) {
target.style.background = '#A855F7';
}
}
Example #2
Source File: index.ts From webapis-playground with MIT License | 6 votes |
function onDragOver(event: DragEvent) {
event.preventDefault();
const target = event.target as HTMLElement;
if (target) {
target.style.borderColor = '#3B82F6';
}
}
Example #3
Source File: index.ts From webapis-playground with MIT License | 6 votes |
function onDrop(event: DragEvent) {
event.preventDefault();
const target = event.target as HTMLElement;
const data = event.dataTransfer.getData('text');
const box = document.getElementById(data) as HTMLElement;
target.appendChild(box);
if (box) {
box.style.background = '#3B82F6';
}
}
Example #4
Source File: index.ts From webapis-playground with MIT License | 6 votes |
function onDragEnter(event: DragEvent) {
event.preventDefault();
const target = event.target as HTMLElement;
const data = event.dataTransfer.getData('text');
const box = document.getElementById(data) as HTMLElement;
target.style.borderColor = '#3B82F6';
if (box) {
box.style.background = '#3B82F6';
}
}
Example #5
Source File: index.ts From webapis-playground with MIT License | 6 votes |
function onDragLeave(event: DragEvent) {
event.preventDefault();
const target = event.target as HTMLElement;
if (target) {
target.style.borderColor = '#DBEAFE';
}
}
Example #6
Source File: file.ts From gateway-ui with BSD 3-Clause "New" or "Revised" License | 6 votes |
export async function handleDrop(ev: DragEvent): Promise<SwarmFile[]> {
const files: SwarmFile[] = []
if (ev.dataTransfer.items) {
const { items } = ev.dataTransfer
const entries = []
for (let i = 0; i < items.length; i++) {
const item = items[i]
const entry = item.webkitGetAsEntry()
if (entry) entries.push(...(await scanFiles(entry)))
}
// This is deliberately a separate loop because item.file() function mutates the dataTransferItems object
for (let i = 0; i < entries.length; i++) {
const f = await fileEntry2File(entries[i])
files.push(f)
}
} else {
// Use DataTransfer interface to access the file(s), this is a fallback as we can not handle directories here (even though this API is newer)
for (let i = 0; i < ev.dataTransfer.files.length; i++) files.push(convertSwarmFile(ev.dataTransfer.files[i]))
}
return files
}
Example #7
Source File: drag.ts From MagicUI with Apache License 2.0 | 6 votes |
export function drop(callback: Function, event: DragEvent<any>) {
event.preventDefault();
const { type, name } = JSON.parse(event.dataTransfer?.getData('component'));
callback({
type,
name,
position: {
clientX: event.clientX,
clientY: event.clientY
}
});
}
Example #8
Source File: FileInput.tsx From yet-another-generic-startpage with MIT License | 5 votes |
FileInput = ({ label, id, onChange, valid }: FileInputProps) => {
const [dragging, setDragging] = useState(false)
const addDrag = (event: DragEvent<HTMLDivElement>) => {
event.preventDefault()
setDragging(true)
}
const removeDrag = (event: DragEvent<HTMLDivElement>) => {
event.preventDefault()
setDragging(false)
}
const handleDrop = (event: DragEvent<HTMLDivElement>) => {
event.preventDefault()
setDragging(false)
const file = event.dataTransfer.items[0].getAsFile()
if (file) onChange?.(file)
}
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (file) onChange?.(file)
}
return (
<Wrapper onDrop={handleDrop} onDragOver={addDrag} onDragLeave={removeDrag}>
<HiddenFileInput as="input" type="file" id={id} onChange={handleChange} />
<Label htmlFor={id} valid={valid} dragging={dragging}>
{label} <Upload />
</Label>
</Wrapper>
)
}
Example #9
Source File: Orderable.tsx From project-loved-web with MIT License | 5 votes |
export function Orderable({ children, enabled, onMoveChild }: OrderableProps) {
const [draggedIndex, setDraggedIndex] = useState<number>();
const [dropIndex, setDropIndex] = useState<number>();
const getClassName = (index: number) => {
if (index !== dropIndex || draggedIndex == null) {
return;
}
if (index < draggedIndex) {
return 'drop-bar-top';
}
if (index > draggedIndex) {
return 'drop-bar-bottom';
}
};
const onDragEnter = (index: number) => {
if (draggedIndex == null) {
return;
}
setDropIndex(index);
};
const onDragOver = (event: DragEvent) => {
if (draggedIndex == null) {
return;
}
event.preventDefault();
};
const onDrop = (event: DragEvent) => {
if (draggedIndex == null || dropIndex == null || draggedIndex === dropIndex) {
return;
}
event.preventDefault();
onMoveChild(draggedIndex, dropIndex);
};
const onDragEnd = () => {
setDraggedIndex(undefined);
setDropIndex(undefined);
};
return (
<>
{children.map((child, index) => (
<div
className={getClassName(index)}
draggable={enabled}
key={child.key}
onDragEnd={onDragEnd}
onDragEnter={() => onDragEnter(index)}
onDragOver={onDragOver}
onDragStart={() => setDraggedIndex(index)}
onDrop={onDrop}
>
{child}
</div>
))}
</>
);
}
Example #10
Source File: ServerListItem.tsx From shadowsocks-electron with GNU General Public License v3.0 | 5 votes |
ServerListItem: React.FC<ServerListItemProps> = props => {
const {
item,
selectedServer,
isLast,
dragTarget,
dragSort,
setDragTarget,
setDragSource
} = props;
const styles = useStyles();
const ref = useRef<HTMLDivElement>(null);
const theme: Theme = useTheme();
const onDragStart = (e: DragEvent<HTMLDivElement>) => {
setCloneElement((e.target as HTMLDivElement).cloneNode(true) as HTMLDivElement);
(e.target as HTMLDivElement).style.opacity = "0.2";
setDragSource(item.id);
e.dataTransfer.setDragImage(img, 0, 0);
};
const onDragEnd = (e: DragEvent<HTMLDivElement>) => {
if (cloneElement) {
(e.target as HTMLDivElement).style.opacity = "1";
dragSort();
cloneElement.remove();
setCloneElement(null);
}
}
const onDragEnter = () => {
if (cloneElement) {
setDragTarget(item.id);
cloneElement.remove();
cloneElement.style.transition = 'all 0.3s linear';
cloneElement.style.border = `dashed 2px ${theme.palette.primary.main}`;
ref.current?.prepend(cloneElement);
}
};
const isInOver = dragTarget.current === item.id;
return (
<>
<div
ref={ref}
draggable={true}
onDragStart={onDragStart}
onDragEnd={onDragEnd}
onDragEnter={onDragEnter}
className={clsx(styles.wrapper, isInOver && styles.highlight)}
>
<If
condition={item.type === 'group'}
then={<ServerListItemGroup {...props} item={(props.item as GroupConfig)} selectedServer={selectedServer} />}
else={<ServerListItemSingle {...props} item={(props.item as Config)} selected={selectedServer === item.id} />}
/>
</div>
{!isLast && <GradientDivider />}
</>
);
}
Example #11
Source File: drag.ts From MagicUI with Apache License 2.0 | 5 votes |
export function allowDrop(event: DragEvent) {
event.preventDefault();
}
Example #12
Source File: drag.ts From MagicUI with Apache License 2.0 | 5 votes |
export function drag(type: string, name: string, event: DragEvent<any>) {
event.dataTransfer?.setData('component', JSON.stringify({type, name}));
}
Example #13
Source File: image-upload.tsx From keycaplendar with MIT License | 4 votes |
ImageUpload = ({ desktop, image, setImage }: ImageUploadProps) => {
const [imageBase64, setImageBase64] = useState("");
const [imageLink, setImageLink] = useState("");
const [imageFromURL, setImageFromURL] = useState(true);
const [dragOver, setDragOver] = useState(false);
const [loading, setLoading] = useState(false);
const [hasImage, setHasImage] = useState(false);
const previewImage = (image: Blob | File) => {
const reader = new FileReader();
reader.readAsDataURL(image);
reader.onloadend = () => {
setImageBase64(reader.result as string);
setHasImage(true);
setLoading(false);
};
};
useEffect(() => {
if (image) {
if (is<string>(image)) {
setImageBase64(image);
setHasImage(true);
} else {
previewImage(image);
}
} else {
setImageBase64("");
setImageLink("");
setImageFromURL(true);
setDragOver(false);
setLoading(false);
setHasImage(false);
}
}, [image]);
const getImageFromURL = (url: string) => {
setLoading(true);
fetch(url)
.then((response) => response.blob())
.then((blob) => {
setLoading(false);
setImage(blob);
})
.catch((err) => {
setLoading(false);
queue.notify({ title: `Failed to fetch image: ${err}` });
});
};
const handleChange = ({
target: { name, value },
}: ChangeEvent<HTMLInputElement>) => {
if (name === "imageLink") {
setImageLink(value);
}
const regex = RegExp("https?://.+(?:.(?:jpe?g|png)|;image)");
if (regex.test(value)) {
getImageFromURL(value);
}
};
const handleDragEnter = (e: DragEvent<HTMLDivElement>) => {
if (!imageFromURL) {
e.preventDefault();
e.stopPropagation();
setDragOver(true);
}
};
const handleDragLeave = (e: DragEvent<HTMLDivElement>) => {
if (!imageFromURL) {
e.preventDefault();
e.stopPropagation();
setDragOver(false);
}
};
const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
if (!imageFromURL) {
e.preventDefault();
e.stopPropagation();
}
};
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
if (!imageFromURL) {
e.preventDefault();
e.stopPropagation();
setLoading(true);
const {
dataTransfer: {
files: [file],
},
} = e;
if (!file.type.includes("image")) {
queue.notify({ title: "Error: file is not an image." });
setDragOver(false);
setLoading(false);
} else {
setImage(file);
setDragOver(false);
}
}
};
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
e.preventDefault();
e.stopPropagation();
setLoading(true);
const {
target: { files },
} = e;
if (files) {
const [file] = files;
setImage(file);
setDragOver(false);
}
};
const fromUrl = () => {
setImageFromURL(true);
};
const fromFile = () => {
setImageFromURL(false);
setImageLink("");
};
const imageTextField = imageFromURL ? (
<TextField
autoComplete="off"
helpText={{
children: "Must be valid link",
persistent: false,
validationMsg: true,
}}
icon="link"
label="Image link"
name="imageLink"
onChange={handleChange}
outlined
pattern="https?://.+\.(?:jpg|jpeg|png)"
value={imageLink}
/>
) : null;
const areaInner = hasImage ? (
<div
className="image-display-image"
style={{
backgroundImage: `url(${imageBase64.replace(
"/keysets%2F",
"/thumbs%2F"
)})`,
}}
/>
) : loading ? null : desktop && !imageFromURL ? (
<div className="drag-label">
<Icon icon={iconObject(<AddPhotoAlternate />, { size: "medium" })} />
<Typography className="caption" tag="p" use="body2">
Drag image here
</Typography>
</div>
) : (
<div className="drag-label">
<Icon icon={iconObject(<AddPhotoAlternate />, { size: "medium" })} />
</div>
);
const loadingIndicator = loading ? (
<div className={classNames("loading-indicator", { image: hasImage })}>
<CircularProgress size="large" />
</div>
) : null;
const actions = !imageFromURL ? (
<CardActions>
<CardActionButtons>
<div className="file-input">
<CardActionButton htmlFor="file-upload" label="Browse" tag="label" />
<input
accept=".png, .jpg, .jpeg"
id="file-upload"
onChange={handleFileChange}
type="file"
/>
</div>
<CardActionButton label="From URL" onClick={fromUrl} />
</CardActionButtons>
</CardActions>
) : (
<CardActions>
<CardActionButtons>
<CardActionButton label="From file" onClick={fromFile} />
</CardActionButtons>
</CardActions>
);
return (
<Card className="image-upload" outlined>
<Typography className="image-upload-title" tag="h3" use="caption">
Image*
</Typography>
<div className="image-upload-form">
<div
className={classNames("image-display", {
image: hasImage,
over: dragOver,
})}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{loadingIndicator}
{areaInner}
</div>
{imageTextField}
</div>
{actions}
</Card>
);
}
Example #14
Source File: AddFile.tsx From gateway-ui with BSD 3-Clause "New" or "Revised" License | 4 votes |
export default function Upload({ setFiles }: Props): ReactElement {
const classes = useStyles()
const ref = useRef<HTMLInputElement>(null)
const navigate = useNavigate()
const [isDragging, setIsDragging] = useState<boolean>(false)
const [agreedToTerms, setAgreedToTerms] = useState(Boolean(window.localStorage.getItem('agreedToTerms')))
useEffect(() => {
if (ref.current !== null) {
ref.current.setAttribute('directory', '')
ref.current.setAttribute('mozdirectory', '')
ref.current.setAttribute('webkitdirectory', '')
}
}, [ref])
const handleAgree = () => {
setAgreedToTerms(true)
window.localStorage.setItem('agreedToTerms', Date.now().toString())
}
const onDragOver = (ev: DragEvent<HTMLDivElement>) => {
ev.preventDefault()
ev.stopPropagation()
setIsDragging(true)
}
const onDrop = async (ev: DragEvent<HTMLDivElement>) => {
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault()
ev.stopPropagation()
setFiles(await handleDrop(ev))
setIsDragging(false)
}
const handleFiles = (fileList: FileList | null) => {
const files = []
if (fileList) for (let i = 0; i < fileList.length; i++) files.push(convertSwarmFile(fileList[i]))
setFiles(files)
}
const onDragLeave = (ev: DragEvent<HTMLDivElement>) => {
ev.preventDefault()
ev.stopPropagation()
setIsDragging(false)
}
if (!agreedToTerms) return <TermsAndConditionsPopup handleAgree={handleAgree} />
return (
<div onDragOver={onDragOver} onDrop={onDrop}>
<>
{isDragging && (
<div onDragLeave={onDragLeave} className={classes.dragOverlay}>
<Typography className={classes.dragOverlayChildren} variant="button">
{text.addFile.dragHeader}
</Typography>
<Typography variant="body1" className={classes.dragOverlayChildren}>
{text.addFile.dragTagline}
</Typography>
</div>
)}
</>
<Layout
top={[
<Header
key="top1"
leftAction={
<IconButton onClick={() => navigate(ROUTES.LANDING_PAGE)}>
<ArrowLeft strokeWidth={1} />
</IconButton>
}
>
{text.addFile.header}
</Header>,
<Typography key="top2" variant="body1">
{text.addFile.tagline}
</Typography>,
]}
center={[
<Button variant="contained" key="center1" component="label" size="large" className={classes.button}>
<Plus strokeWidth={1} />
{text.addFile.addFileAction}
<input
type="file"
hidden
multiple
onChange={event => {
handleFiles(event.target.files)
}}
/>
<Plus style={{ opacity: 0 }} />
</Button>,
<Button variant="contained" key="center2" component="label" size="large" className={classes.button}>
<Plus strokeWidth={1} />
{text.addFile.addFolderAction}
<input
type="file"
hidden
multiple
ref={ref}
onChange={event => {
handleFiles(event.target.files)
}}
/>
<Plus style={{ opacity: 0 }} />
</Button>,
]}
bottom={[
<Typography key="bottom" variant="body1">
{text.addFile.disclaimer}
</Typography>,
]}
/>
</div>
)
}