I am a newbie in Reactjs, I am trying to create a function where a circle is created at the position of a mouse click. The problem is that everytime i clicked, the error "e.getClickCoords is not a function" is shown.
Also, there is an error "shapes are undefined" in function addCircle despite the fact that I passes the parameter. I have no idea how to solve it :(
Here is the code:
import React, { useState } from 'react';
import styled from "styled-components";
import './mysass.scss';
import { Stage, Layer, Circle, Line, Text } from "react-konva";
import { shapes } from 'konva/lib/Shape';
import ReactCursorPosition from 'react-cursor-position';
function initiate_shape() {
const initial_shape = [];
alert("Hello there");
for (var i = 0; i < 2; i++) {
initial_shape.push({
id: i,
x: Math.random() * window.innerWidth,
y: Math.random() * window.innerHeight
});
}
return initial_shape;
}
const getClickCoords = (event) => {
var e = event.target;
var dim = e.getBoundingClientRect();
var cx = event.clientX - dim.left;
var cy = event.clientY - dim.top;
alert(cx + cy);
return [cx, cy];
/*
var cX = event.clientX;
var sX = event.screenX;
var cY = event.clientY;
var sY = event.screenY;
var coords1 = "client - X: " + cX + ", Y coords: " + cY;
var coords2 = "screen - X: " + sX + ", Y coords: " + sY;
alert(coords1);
alert(coords2);
*/
//return [cX, cY];
}
function addCircle(event,shapes, shape_id) {
let [sX, sY] = getClickCoords(event);
alert("x: " + sX + " y: " + sY);
shapes.push({id: shape_id, x: sX, y: sY});
shape_id += 1
}
const FunctionApp = (event) => {
const shape_id = 2;
const initial_shape = initiate_shape();
const [shapes, setShapes] = React.useState(initial_shape);
alert(shapes);
const [connectors, setConnectors] = React.useState([]);
const [fromShapeId, setFromShapeId] = React.useState(null);
//let cx = coordinates[0];
//let cy = coordinates[1];
return (
<Stage width={window.innerWidth} height={window.innerHeight} onclick={addCircle}>
<Layer>
{connectors.map(con => {
const from = shapes.find(s => s.id === con.from);
const to = shapes.find(s => s.id === con.to);
return (
<Line
key={con.id}
points={[from.x, from.y, to.x, to.y]}
stroke="black"
/>
);
})}
{shapes.map(shape => (
<Circle
x={shape.x}
y={shape.y}
key={shape.id}
fill={fromShapeId === shape.id ? "red" : "green"}
radius={20}
shadowBlur={10}
onClick={() => {
if (fromShapeId) {
const newConnector = {
from: fromShapeId,
to: shape.id,
id: connectors.length
};
setConnectors(connectors.concat([newConnector]));
setFromShapeId(null);
//connectors.concat([newConnector]);
//fromShapeId = null;
} else {
setFromShapeId(shape.id);
//fromShapeId = shape.id;
}
}}
/>
))}
<Text text="Click on on circle then on another to connect them" />
</Layer>
</Stage>
)
}
export default FunctionApp;
Thanks u in advance