Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center react-draggable element on start? (modal, div)

How to center react-draggable element on start? I have a modal that is wrapped by react-draggable a component. I would like to after the modal is open, center his position in a browser. I try pass to a defaultPosition a percentage value but I'm not able to pass percentage defaultPostion={{ x: 50%, y: 50% };} but without result.

like image 404
Pyot Avatar asked Jan 30 '26 08:01

Pyot


1 Answers

React draggable has an option named positionOffSet which gives us a chance to set the initial offset of the draggable element. This is different than the defaultPosition and accepts %value. You can check the React Draggable docs for details.

<Draggable positionOffset={{ x: '-50%', y: '-50%' }}}>
  <div className='myElement'>
    This is my draggable element
  </div>
</Draggable/>

Now, all we need to do is to add few styles to our element like so:

.myElement{z-index:999; position: absolute; top: 50%; left: 50%;}

This will center the modal element in the middle of the page, no matter what dimensions it has.

like image 85
Enes Avatar answered Jan 31 '26 21:01

Enes