Skip to content

Instantly share code, notes, and snippets.

@rtm7777
Created February 5, 2018 15:33
Show Gist options
  • Save rtm7777/be857f411148e6d55210c1293297096d to your computer and use it in GitHub Desktop.
Save rtm7777/be857f411148e6d55210c1293297096d to your computer and use it in GitHub Desktop.
simple vertical react divider component
import React, { Component } from 'react'
const Left = () => <div /> // Component to be placed into left section of divider
const Right = () => <div /> // Component to be placed into right section of divider
class Divider extends Component {
constructor(props) {
super(props)
this.dragging = false
this.leftLim = 0.1 // min width of left container (0.1...0.9)
this.rightLim = 0.9 // max width of left container (0.1...0.9) SHOULD be less than minimum
}
componentWillMount() {
window.addEventListener('mouseup', () => {
if (this.dragging) {
this.dragging = false
window.removeEventListener('mousemove', this.move)
}
})
}
componentWillUnmount() {
window.removeEventListener('mouseup')
}
move = (e) => {
const xPosition = e.pageX - this.container.offsetLeft
let cur = xPosition
if (xPosition < this.minWidth) cur = this.minWidth
if (xPosition > this.maxWidth) cur = this.maxWidth
const left = (cur * 100) / this.containerWidth
const right = 100 - left
this.leftContainer.style.width = `${left}%`
this.rightContainer.style.width = `calc(${right}% - ${this.dividerWidth}px)`
}
startDragging = (e) => {
this.dragging = true
this.containerWidth = this.container.offsetWidth
this.dividerWidth = e.currentTarget.offsetWidth
this.minWidth = this.containerWidth * this.leftLim
this.maxWidth = (this.containerWidth * this.rightLim) - this.dividerWidth
window.addEventListener('mousemove', this.move)
}
render() {
return (
<div ref={(el) => { this.container = el }} className="divider-container">
<div className="left" ref={(el) => { this.leftContainer = el }}>
<Left />
</div>
<div className="divider" onMouseDown={this.startDragging} />
<div className="right" ref={(el) => { this.rightContainer = el }}>
<Right />
</div>
</div>
)
}
}
export default Divider
.divider-container {
display: flex;
width: 100%;
overflow: hidden;
.divider {
width: 10px;
cursor: col-resize;
background-color: #b55;
}
.left {
width: 18%; // Initial width of left component
background-color: #aaa;
}
.right {
width: calc(~'82% - 10px'); // Intial width of right component according to left component and divider width
background-color: rgb(131, 192, 131);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment