Skip to content

Instantly share code, notes, and snippets.

@ristaa
Last active February 12, 2019 11: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 ristaa/243fab2fb2a86dbea2aff433025c71ab to your computer and use it in GitHub Desktop.
Save ristaa/243fab2fb2a86dbea2aff433025c71ab to your computer and use it in GitHub Desktop.
React hooks
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
}
: null;
}
function useHexToRgba(hexColor, opacity) {
const [rgbColor, setRgbColor] = useState(null);
function handleColorChange(color) {
setRgbColor(color);
}
useEffect(() => {
var isOk = /^#[0-9A-F]{6}$/i.test(hexColor);
var opOK = /^(0(\.\d+)?|1(\.0+)?)$/.test(opacity);
if(isOk && opOK){
const newRGBObj = hexToRgb(hexColor);
const newRGBcolor = `(${newRGBObj.r}, ${newRGBObj.g}, ${newRGBObj.b}, ${opacity})`;
handleColorChange(newRGBcolor);
} else {
handleColorChange(`(255, 255, 255, 0)`);
}
}, [hexColor, opacity]);
return rgbColor;
}
function App() {
const [colorValue, setColorValue] = useState(0);
const [opacityValue, setOpacityValue] = useState(0);
const colorToRGB = useHexToRgba(colorValue, opacityValue);
const backColor = {
backgroundColor: `rgba${colorToRGB}`
};
return (
<div className="App">
<h1>Hex Color to RGB</h1>
<p>Please enter correct values</p>
<p>First input: Any hex number (with #), for example: #229922</p>
<p>Second input: Any number between 0 and 1, for example: 0.5</p>
<input type="text" value={colorValue} onChange={event => setColorValue(event.target.value)} placeholder="e.g. #229922"/>
<input type="text" value={opacityValue} onChange={event => setOpacityValue(event.target.value)} placeholder="e.g. 0.2"/>
<h1 style={backColor}>rgba{colorToRGB}</h1>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment