Chase R Lewis
Chase R Lewis

Reputation: 2307

Open file dialog from React Component using Electron

So I'm aware without react on the render thread I can do this to open a file dialog.

const {dialog} = require('electron').remote
dialog.showOpenDialog({properties: ['openFile']}))

I'm trying to use react and learn the workflows of React & Electron though. Doing the require gives me the following error.

TypeError: fs.existsSync is not a function
getElectronPath
   5 | var pathFile = path.join(__dirname, 'path.txt');
   6 | 
   7 | function getElectronPath() {
>  8 |   if (fs.existsSync(pathFile)) {
   9 |     var executablePath = fs.readFileSync(pathFile, 'utf-8');
  10 | 
  11 |     if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
View compiled
(anonymous function)
  18 |   }
  19 | }
  20 | 
> 21 | module.exports = getElectronPath();
View compiled

Unsure what I can do to make this work. Should be a pretty simple canvas drawing app, but i do need to enumerate images in folders & give file dialog capabilities to the app. Any ideas how to remedy this issue?

Upvotes: 3

Views: 7630

Answers (1)

Chase R Lewis
Chase R Lewis

Reputation: 2307

I found a solution. You can run a preload.js into a window on creation and then call the items like javascript objects.

Found this issue on the github https://github.com/electron/electron/issues/9920

  mainWindow = new BrowserWindow({
    width: 800, 
    height: 600,
    webPreferences: {
      nodeIntegration: false,
      preload: __dirname + '/preload.js'
    }
  });

Preload.js

const { dialog } = require('electron').remote;
window.electron = {};
window.electron.dialog = dialog;

Then anything I want to load into the window I can just add to the window.electron object and call it with no issues. React pre-compiler is more the issue than anything with electron.

Upvotes: 8

Related Questions