If you're looking for an example of two columns adjusting their width based on mouse movement, check out this page from W3Schools. I'm trying to implement this feature in my React app, but I'm unsure of how to proceed.
Below is the JSX code snippet:
... return(
<>
Container fluid>
<Row>
<Col xs={3} style={{ backgroundColor: "red" }}>
Column 1
</Col> //here Want to create a middle bar between two columns and add functionality like increase and decrease width depending on the mouse left and right move.
<Col style={{ backgroundColor: "black" }}>column 2</Col>
</Row>
</Container>
</>
)
I attempted to achieve this functionality by using the following code:
const admin = () => {
const [leftColumnWidth, setLeftColumnWidth] = useState(3);
const [isResizing, setIsResizing] = useState(false);
const handleMouseDown = () => {
setIsResizing(true);
};
const handleMouseUp = () => {
setIsResizing(false);
};
const handleMouseMove = (e) => {
if (!isResizing) return;
const containerWidth = e.currentTarget.offsetWidth;
const mouseX = e.clientX;
const newLeftColumnWidth = Math.min(
Math.max((mouseX / containerWidth) * 100, 10),
90
);
setLeftColumnWidth(newLeftColumnWidth);
};
return (
<>
<Container fluid onMouseMove={handleMouseMove} onMouseUp={handleMouseUp}>
<Row>
<Col
xs={leftColumnWidth}
style={{
backgroundColor: "red",
borderRight: "1px solid black",
height: "100vh",
overflow: "hidden",
}}
>
1 of 3
<div
style={{
width: "10px",
cursor: "col-resize",
position: "absolute",
right: 0,
top: 0,
bottom: 0,
}}
onMouseDown={handleMouseDown}
></div>
</Col>
<Col style={{ backgroundColor: "black", height: "100vh" }}>
2 of 3 (wider)
</Col>
</Row>
</Container>
</> );
};
However, the above code did not produce the desired result. You can view the outcome here.
The solution provided by Khurram Shafique worked, but I would also like to learn how to implement it for sections B and C. Check out my updated code below:
<div
ref={containerRef}
style={{ display: "flex", height: "100vh", width: "100%" }}
>
<div
style={{
width: `${columnWidth}%`,
background: "lightgrey",
overflow: "auto",
}}
>
<div style={{ height: "500px", padding: "16px" }}>Column A</div>
</div>
<div
ref={handleRef}
onMouseDown={onMouseDown}
style={{ cursor: "ew-resize", width: "10px", background: "grey" }}
/>
<div
style={{
width: `${100 - columnWidth}%`,
display: "flex",
flexDirection: "column",
}}
>
<div
style={{
background: "lightblue",
overflow: "auto",
flex: "70%",
}}
>
<div style={{ height: "300px", padding: "16px" }}>Section B</div>
</div>
<div
style={{
background: "lightgreen",
height: "30%",
overflow: "auto",
}}
>
Section C
</div>
</div>
</div>