How can I set minimum width for not allowing drag left to no width in the following sample?
const App = () => {
const [initialPos, setInitialPos] = React.useState(null);
const [initialSize, setInitialSize] = React.useState(null);
const initial = (e) => {
let resizable = document.getElementById('Resizable');
setInitialPos(e.clientX);
setInitialSize(resizable.offsetWidth);
}
const resize = (e) => {
let resizable = document.getElementById('Resizable');
resizable.style.width = `${parseInt(initialSize) parseInt(e.clientX - initialPos)}px`;
}
return(
<div className = 'Block'>
<div id = 'Resizable'/>
<div id = 'Draggable'
draggable = 'true'
onDragStart = {initial}
onDrag = {resize}
/>
</div>
);
}
ReactDOM.render(<App/>, document.getElementById('root'));
https://codepen.io/erikmartinjordan/pen/dyMEXJb?editors=0110
CodePudding user response:
You can adjust your resize function to limit the width.
const resize = (e) => {
let resizable = document.getElementById('Resizable');
let newWidth = parseInt(initialSize) parseInt(e.clientX - initialPos);
if (newWidth < 200) {
newWidth = 200;
}
resizable.style.width = `${newWidth}px`;
}
You can set 200 to be any maximum width. Just don't forget to change both 200 values, or even better make a variable for it!
CodePudding user response:
This will allow you to move the end to either left or right with maximum of 200 pixels.
const initial = (e) => {
let resizable = document.getElementById("Resizable");
// lock the start position
if (initialPos == null) {
setInitialPos(e.clientX);
setInitialSize(resizable.offsetWidth);
}
};
const resize = (e) => {
let resizable = document.getElementById("Resizable");
// check for the absolute distance from the start point
if (Math.abs(e.clientX - initialPos) < 200) {
resizable.style.width = `${
parseInt(initialSize) parseInt(e.clientX - initialPos)
}px`;
}
};
