Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Place <div> at x,y coordinate in React

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?

like image 250
nopassport1 Avatar asked Aug 15 '19 12:08

nopassport1


People also ask

How do you position a div in a specific coordinates React?

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.

How do I change position of element in React?

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.

Can you use DIV in React?

No, you cannot use the <div> element inside a react native component because React Native does not have a DOM.


1 Answers

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.

like image 100
Twiggeh Avatar answered Sep 30 '22 00:09

Twiggeh