Skip to content

Instantly share code, notes, and snippets.

@mbeaudru
Created March 22, 2017 09:06
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbeaudru/d473014009ef12bc9eef076f3fa004ff to your computer and use it in GitHub Desktop.
Save mbeaudru/d473014009ef12bc9eef076f3fa004ff to your computer and use it in GitHub Desktop.
Checkbox with styled-components
import React, { Component, PropTypes } from 'react';
import styled from 'styled-components';
class Checkbox extends Component {
render() {
return (
<Styled
onClick={() => this.props.onChange(!this.props.checked)}
>
<input
type="checkbox"
checked={this.props.checked}
/>
<label>{this.props.label}</label>
</Styled>
);
}
static propTypes = {
checked: PropTypes.bool,
onChange: PropTypes.func,
label: PropTypes.string,
}
}
export default Checkbox;
const Styled = styled.div`
display: inline-block;
> input {
opacity: 0;
}
> input + label {
position: relative; /* permet de positionner les pseudo-éléments */
padding-left: 25px; /* fait un peu d'espace pour notre case à venir */
cursor: pointer; /* affiche un curseur adapté */
&:before {
content: '';
position: absolute;
left:0; top: 1px;
width: 17px; height: 17px; /* dim. de la case */
border: 1px solid #aaa;
background: #f8f8f8;
border-radius: 3px; /* angles arrondis */
box-shadow: inset 0 1px 3px rgba(0,0,0,.3) /* légère ombre interne */
}
&:after {
content: '✔';
position: absolute;
top: -1px; left: 2px;
font-size: 16px;
color: #09ad7e;
transition: all .2s; /* on prévoit une animation */
}
}
> input:not(:checked) + label {
&:after {
opacity: 0; /* coche invisible */
transform: scale(0); /* mise à l'échelle à 0 */
}
}
> input:disabled:not(:checked) + label {
&:before {
box-shadow: none;
border-color: #bbb;
background-color: #ddd;
}
}
> input:checked + label {
&:after {
opacity: 1; /* coche opaque */
transform: scale(1); /* mise à l'échelle 1:1 */
}
}
> input:disabled:checked + label {
&:after {
color: #999;
}
}
> input:disabled + label {
color: #aaa;
}
> input:checked:focus + label, input:not(:checked):focus + label {
&:before {
border: 1px dotted blue;
}
}
`;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment