Skip to content

Instantly share code, notes, and snippets.

@righ
Last active July 12, 2018 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/978385312c460dc132a2dfdbf0df6beb to your computer and use it in GitHub Desktop.
Save righ/978385312c460dc132a2dfdbf0df6beb to your computer and use it in GitHub Desktop.
React customized checkbox
import React from 'react'
import './checkboxWidget.styl'
let defaultStyle = {width: 22, height: 22}
const CheckBox = (props) => {
let onClick = () => !props.readonly && !props.disabled ? props.handleChange() : null
let borderColor = props.borderColor ? props.borderColor : '#aaa'
let backgroundColor = props.checked ? props.backgroundColor ? props.backgroundColor : '#transparent' : 'transparent'
let style = Object.assign({}, defaultStyle, props.style)
let checkLeft = ((style.width - 15) - style.width * 0.27) / 2
let checkTop = ((style.height - 20) - style.height * 0.4) / 2
return <div className='checkbox-wrapper' style={{...style, width: 'auto'}}>
<input
type="checkbox"
name={props.name}
value={props.value}
checked={props.checked}
disabled={props.disabled}
/>
<div
className={`checkbox${props.readonly ? ' checkbox-readonly' : ''}${props.disabled ? ' checkbox-disabled' : ''}`}
style={{width: style.width}}
onClick={onClick}
>
<div className='checkbox-before' style={{borderColor, backgroundColor}} />
<div className='checkbox-after' style={{top: checkTop > 0 ? checkTop : 0, left: checkLeft > 0 ? checkLeft : 0}} />
</div>
<span
className='checkbox-text'
style={{marginLeft: 3, ...props.textStyle}}
onClick={onClick}
>{props.children}</span>
</div>
}
export default CheckBox
.checkbox-wrapper
display inline-block
margin 0
box-sizing border-box
input[type="checkbox"]
position absolute
opacity 0
outline none
-webkit-appearance none
-moz-appearance none
appearance none
&:checked
& + .checkbox
& .checkbox-after
border 2px solid #000
border-width 0 2px 2px 0
-webkit-transform rotate(45deg)
-ms-transform rotate(45deg)
transform rotate(45deg)
.checkbox
margin 0
height 100%
position relative
cursor pointer
display inline-block
vertical-align middle
& .checkbox-before, & .checkbox-after
position absolute
top 0
left 0
box-sizing border-box
& .checkbox-before
z-index 0
background-color transparent
width 100%
height 100%
border solid 2px
border-radius 5px
& .checkbox-after
z-index 1
margin 5px 8px
width 27%
height 40%
&.checkbox-readonly
cursor default
&.checkbox-disabled
opacity 0.5
cursor not-allowed
.checkbox-text
display inline-block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment