Reputation: 57
I'm trying to change a divs background color based on the input of the user. I want to set the state's key to hue with the value being the user's input. I then want to take that state and inject it into another state key called color's value. I want the color value to be the value of the hue's state using hsl in chromajs.
When I try to input the color red, hue's state changes to red. Also, color's value becomes red on the first "r" keystroke, then after any additional keystrokes it changes to black. It shows a value of rgb(0, 0, 0, 1) in Dev Tools.
I can't figure out why it changes to red on a single letter, and why it changes to black when colors value should be chroma('red', 1, 0.5, "hsl").
What am I not understanding about the use of chromajs?
import React from 'react';
import './App.css';
import chroma from 'chroma-js';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
hue: '',
color: ''
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.setState({
hue: e.target.value,
color: chroma(this.state.hue, 1, 0.5, "hsl")
})
}
render() {
const style = {
background: this.state.color,
height: 200
}
return (
<div style={style}>
<input value={this.state.hue} onChange={this.handleChange}></input>
</div>
);
}
}
export default App;
Upvotes: 1
Views: 247
Reputation: 2565
The coloration of your div will work if you will change your handleChange function like that:
handleChange(e) {
const color = chroma.valid(e.target.value)
? chroma(e.target.value).saturate().alpha(0.5) : chroma("white");
this.setState({
hue: e.target.value,
color,
});
}
First, we need to validate the user input via the chroma.valid() function. After that, we can set the saturation & alpha value. If the user input will not pass the chroma validation, it will use white color.
You can see it working here: https://codesandbox.io/s/rmmk0j5mmp?fontsize=14
If you want to construct your color via the way you started, you need to pass a hue angle, not a color name. From the docs:
You can construct colors from different color spaces by passing the name of color space as the last argument. Here we define the same color in HSL by passing the hue angle (0-360) and percentages for saturation and l*ightness:
chroma(330, 1, 0.6, 'hsl')
Source: https://gka.github.io/chroma.js/
Upvotes: 2