Created
November 30, 2017 12:46
-
-
Save EliyaD/496d8fe11483d3722429062f48cb03eb to your computer and use it in GitHub Desktop.
Material UI color picker using react-color
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' // v16.1.1 | |
import { withStyles } from 'material-ui/styles' // v1.0.0-beta.21 | |
import { SketchPicker } from 'react-color' // v2.13.8 | |
import Input, { InputLabel, InputAdornment } from 'material-ui/Input' | |
import { FormControl } from 'material-ui/Form' | |
import IconButton from 'material-ui/IconButton' | |
const styles = theme => ({ | |
root: { | |
position: 'relative', | |
marginTop: theme.spacing.unit * 3 | |
}, | |
color: { | |
width: 20, | |
height: 20, | |
borderRadius: 2, | |
}, | |
popover: { | |
position: 'absolute', | |
right: 0, | |
zIndex: 2 | |
}, | |
cover: { | |
position: 'fixed', | |
top: 0, | |
right: 0, | |
bottom: 0, | |
left: 0 | |
} | |
}) | |
class ColorPicker extends Component { | |
state = { | |
displayColorPicker: false, | |
color: this.props.baseColor || '000000', | |
} | |
handleClick = () => { | |
this.setState({ displayColorPicker: !this.state.displayColorPicker }) | |
} | |
handleClose = () => { | |
this.setState({ displayColorPicker: false }) | |
} | |
handleChange = color => { | |
this.setState({ color: color.hex.substr(1) }) | |
} | |
handleInputChange = event => { | |
this.setState({ color: event.target.value }) | |
} | |
render () { | |
const { classes } = this.props | |
const color = { background: '#' + this.state.color } | |
const colorPicker = ( | |
<div className={classes.popover}> | |
<div className={classes.cover} onClick={this.handleClose}/> | |
<SketchPicker color={('#' + this.state.color)} onChange={this.handleChange}/> | |
</div> | |
) | |
return ( | |
<div className={classes.root}> | |
<FormControl fullWidth> | |
<InputLabel htmlFor={this.props.colorLabel}>{this.props.colorLabel}</InputLabel> | |
<Input | |
id={this.props.colorLabel} | |
value={this.state.color} | |
onChange={this.handleInputChange} | |
startAdornment={<InputAdornment position="start">#</InputAdornment>} | |
endAdornment={ | |
<InputAdornment position="end"> | |
<IconButton onClick={this.handleClick}> | |
<div className={classes.color} style={color}/> | |
</IconButton> | |
</InputAdornment> | |
} | |
/> | |
</FormControl> | |
{this.state.displayColorPicker ? colorPicker : null} | |
</div> | |
) | |
} | |
} | |
export default withStyles(styles)(ColorPicker) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment