-1

I am trying to use Robot.js inside of a React.js application. I have Robot.js installed and can run it to get the results in a separate file. I cannot find a way to run Robot.js inside a React component because I get an error "robot.getMousePos()" is not a function. All I really need is the value of "hex". Is there a way to export the variable into my react component, Or even better run the Robot.js code in the same component without getting errors?

This is the Robot.js example:

const color = () => {
  // Get pixel color under the mouse.
  var robot = require("robotjs");

  // Get mouse position.
  var mouse = robot.getMousePos();

  // Get pixel color in hex format.
  var hex = robot.getPixelColor(mouse.x, mouse.y);
  console.log("#" + hex + " at x:" + mouse.x + " y:" + mouse.y);
};

color();

it returns the value of "hex" which is equal to the hexidecimal color under the mouse at the given x and y coords (#1e1e1e at x:746 y:511)

I am trying to get that output into my React component whose code is here:

import React from "react";

const Robot = () => {
  return (
    <div>
      <h1>Robot</h1>
    </div>
  );
};

export default Robot;
user3109127
  • 49
  • 1
  • 7

2 Answers2

2

Robot.js is a library for desktop automation in Node.js.

React is a library for doing DOM processing in a browser.

You can't run code that depends on Node.js in a browser.

If you want these two bits of code to work together then you'll need to write a web service that they can communicate through (or run your code with something like Electron and then use the IPC API to communicate between the main and renderer processes).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Indeed you will have to run it with some buddy as Electron. I paste below a briefing about how you could reach it with Electron from here:

I was having a similar issue.

First I deleted entire node_modules directory and reinstalled them again by running npm installin project directory (you have to define all modules&versions in a package.json file for that).

Then removed robotjs from node_modules directory manually. And then ran .\node_modules.bin\electron-rebuild.cmd.

After that I installed robotjs again by npm install robotjs.

Then cd .\node_modules\robotjs and node-gyp rebuild --runtime=electron --target=1.3.3 --disturl=https://atom.io/download/atom-shell --abi=48 (1.3.3 is current version of electron)

and problem solved!

I had a similar issue, hopefully I was already using Electron and this worked fine.

CxrlosKenobi
  • 94
  • 1
  • 6