I want to bring a draggable box to the front when I click on it or drag it.
I don't know in advance the maximum number of such boxes because I have a button that creates a new draggable box when the user clicks on the button.
The button should always be on top no matter how many boxes there are, so its z-index should always be the greatest.
So these are my problems:
- How to bring a box to the front when the user clicks on it.
- How to make the button stay at the front.
And I am new to ReactJS.
This is what I currently have in MyComponent.js
import React, { useState } from 'react';
import Draggable from 'react-draggable';
function MyComponent() {
const [currZIndex, setZIndex] = useState(0);
const bringForward = () => {
setZIndex(currZIndex + 1);
}
return (
<Draggable onMouseDown={bringForward}>
<div className="mydiv" style=></div>
</Draggable>
);
}
The problem of my current implementation is that each component knows only its own z-index, but does not know what is the current highest z-index. And z-index increases whenever I click on any div, so this makes the z-indexes unnecessarily large.
If div1 has a z-index of 6 and div2 has a z-index of 2, I have to click div2 5 times to make its z-index become 7 in order to bring div2 to the front.
I still haven't come up with an idea on how to deal with the z-index of the button.
Fyr this is what I have in App.js
import React, { useState } from 'react';
import MyComponent from './MyComponent';
function App() {
const [componentList, setComponentList] = useState([]);
function addNewComponent() {
setComponentList(componentList.concat(<MyComponent key={componentList.length} />));
}
return (
<div>
<button onClick={addNewComponent}>New Component</button>
{componentList}
</div>
);
}
from Bring draggable div to the front in React.js when user clicks on it
No comments:
Post a Comment