Reputation: 111
Im trying to build a app using Tauri and React, it will have icons that can be changed replacing the default img by a new img, the problem is how can I load a image from a local directory an image, in this project Im using react with typescript
EDIT: To extends my problem, when I try to load a image from react i got the next error in the developer tools: "Failed to load resource: the server responded with a status of 404 (Not Found)"
With the next code:
export type ItemType = "File" | "Folder"
interface ItemProps {
itemType: ItemType,
itemName: string | undefined
}
function Item(props: ItemProps) {
return (
<div>
<img src={"$HOME/.config/miguel-file-manager/file_explorer_icons/icons8-file-48.png"}/>
{props.itemName}
</div>
)
}
export default Item
Upvotes: 3
Views: 3003
Reputation: 382
You have to add the following to your tauri.conf.json
file:
{
"$schema": "../node_modules/@tauri-apps/cli/schema.json",
"tauri": {
"allowlist": {
"protocol": {
"asset": true,
"assetScope": [
"$DOCUMENT/**",
]
}
}
}
}
A React component has to convert this local path into an asset path in order to render it:
import { documentDir, join } from '@tauri-apps/api/path';
import { convertFileSrc } from '@tauri-apps/api/tauri';
import { useEffect, useState } from 'react';
function LocalImage() {
const [imagePath, setImagePath] = useState<string | null>(null);
async function updatePaths() {
setImagePath(convertFileSrc(await join(await documentDir(), 'some-dir', 'some-image.jpg')));
}
useEffect(() => {
updatePaths();
}, []);
return <img src={imagePath || ''} alt="Some Image" />;
}
If the image changes over time but the path stays constant, you can use the following to reload the image every 5 seconds:
function LocalImage() {
const [imagePath, setImagePath] = useState<string | null>(null);
const [timestamp, setTimestamp] = useState<number>(new Date().getTime());
async function updatePaths() {
setImagePath(convertFileSrc(await join(await documentDir(), 'some-dir', 'some-image.jpg')));
}
useEffect(() => {
updatePaths();
const interval = setInterval(() => {
setTimestamp(new Date().getTime());
}, 5000);
return () => clearInterval(interval);
}, []);
return <img src={(imagePath || '') + `?${timestamp}`} alt="Some Image" />;
}
Upvotes: 0