I'm writing a desktop application using React and Electron. In this application I would like to add a button that, when clicked, will open a "File Explorer" for the user in a specific path.
This means I don't need to select and upload files.
All I need to do is open "File Explorer" so that the user can view the files. For example: the photo below shows what the user should see
The secure way to communicate between your renderer process (i.e. your React code) and your main process is to use IPC and a preload file. Then you can use shell.openPath()
to open the file explorer to a given path. For example:
Main
const { app, BrowserWindow, ipcMain, shell } = require("electron");
app.whenReady().then(() => {
new BrowserWindow({
webPreferences: {
preload: path.join(__dirname, "preload.js") // Link your preload file
}
});
ipcMain.on("openInExplorer", (_event, path) => {
shell.openPath(path); // Open the given path
});
});
Preload
const { contextBridge, ipcRenderer } = require("electron");
contextBridge.exposeInMainWorld("electronAPI", {
openInExplorer: (path) => {
ipcRenderer.send("openInExplorer", path);
}
});
Renderer
const handleClick = (path) => {
window.electronAPI.openInExplorer(path);
};