I have a simple component which looks like this:
import React from "react";
import './MyContainer.css';
class MyContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
showWhereClicked = (e) => {
console.log(`you have clicked X:${e.screenX} Y:${e.screenY}`);
// do stuff
}
render() {
return (
<div className="myContainer" onClick={this.showWhereClicked}>
I am 500px tall.
</div>
);
}
}
export default MyContainer;
Whenever I click anywhere inside <MyContainer />
, I get a console message giving me an X and Y coordinate of where I clicked on screen.
I wish to place a <div>
inside at the X and Y location of my mouse click. Ideally a box or something, say 100x100px wide.
Later I wish to implement a way for me to freely move these <div>
components around the screen.
How can I achieve this?
You can set the position of any DOM-Element with position: absolute; , top : yCoordinate and left : xCoordinate css attributes. You can then set those in any shape or form and the desired result should be visible.
Approach: We are going to use following steps: Assume the position of our element is 0 on x-coordinate and 0 on y-coordinate. Then we will add/subtract some value from x/y coordinate depending on the direction we are moving.
No, you cannot use the <div> element inside a react native component because React Native does not have a DOM.
The way I would handle this is by using css in js
.
You can set the position of any DOM-Element with position: absolute;
, top : yCoordinate
and left : xCoordinate
css attributes.
// take control over the style of a component
const [style, setStyle] = useState(initialStyle);
const setCoordinates = (x,y) => {
// You don't need whitespace in here, I added it for readability
// I would recommend using something like EmotionJS for this
return `position:absolute;
left:${x}px;
top:${y}px;`
}
...
return(
<div
style = {style}
onClick = { e => {
const newStyle =
setCoordinates(e.target.screenX,
e.target.screenY);
setStyle(newStyle);
}}
></div>)
You can then set those in any shape or form and the desired result should be visible. You won't need to redraw anything, because the DOM didn't change, just the css.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With