Home > database >  I want to convert HEX color to RGB color with input type="color" in React.js
I want to convert HEX color to RGB color with input type="color" in React.js

Time:01-24

What I want to achieve is I would like to convert the HEX format color to RGB color and make a POST request with input type="color".

Issue/error message

The contents of hexToRGB() are always [0, 0, 0] and I can't change color. When I move color picker, console.log(e.target.value) shows like #944242 (example) in console so I'm sure works I don't know how to covert HEX color to RGB color with input type="color" in React.js

I refer the following link but nothing works...

https://codepen.io/urosurosevic/pen/pagxYE

const LightDetailCondo = () => {

  const [hex_value, setHexValue] = useState("#fffff");
  
  const hexToRGB = (hex_value) => {
     hex_value = '0x'   hex_value
     let r = hex_value >> 16 & 0xFF
     let g = hex_value >> 8 & 0xFF
     let b = hex_value & 0xFF
     return `[${r}, ${g}, ${b}]`
  }

  const handleSliderChange2 = (e) => {
    lightOn(e.target.value)
    setHexValue(e.target.value)
    console.log(e.target.value)
    
  }

  console.log(hexToRGB())


  const lightOn = async() => {
    console.log("Body sent to server", {
    rgb_color: hexToRGB(),
  })
    await axios.post('xxx.com',
      {
        rgb_color: hexToRGB(),
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${cookies.get('accesstoken')}`
        },
      })
      .then(result => {
        console.log('Color Changed!');
      })
      .catch(err => {
        console.log('Missed Color Changed!');
      });
  }



    useEffect(() => {

      }, []);



  return (
    <div>
        <input type="color" name="favorite_color" onChange={handleSliderChange2}>
    </div>
    );
}
export default LightDetailCondo;

CodePudding user response:

Your hexToRGB function expects an argument with the hex value. You call it without parameters so it is always undefined. You also use the same name for the parameter as the state variable, so inside the method you are actually shadowing the outer one.

You can

  1. remove the parameter so that it uses the outer hex_value
  2. pass the outer hex_value as a parameter to the method

Something like

const hexToRGB = () => {
  const numericValue = parseInt(hex_value, 16);
  const r = numericValue >> 16 & 0xFF;
  const g = numericValue >> 8 & 0xFF;
  const b = numericValue & 0xFF;
  return `[${r}, ${g}, ${b}]`
}

CodePudding user response:

Maybe you can use this:

<script>
  let d = "#abd450".replace("#" ,"")
   let c2hex = `rgba(${Array.from(d).map((a , _) =>  _  % 2 == 0 ?  parseInt(d[_]   d[_   1] , 16)   "," : null ).join("")} 1)`
  console.log(c2hex)

   //2nd method =>
   const hex2rgb = hex => [...hex.match(/\w\w/g)].map(x => parseInt(x, 16));
   hex2rgb("#40abdc")

</script>
  • Related