Home > Blockchain >  how to handle react-color input should not allow more than 6 digits for hex values?
how to handle react-color input should not allow more than 6 digits for hex values?

Time:05-03

In the given image you can see that I'm able to add more than six hexadecimal values in the Input field, how to avoid that!

enter image description here

CodePudding user response:

You can attach an event handler on the inputs onChange and slice the input string to only be 6 characters long.


const [color, setColor] = useState("");

function txtColorChange(e) {
    setColor(e.target.value.slice(0,6));
}

...

<input value={color} onChange={(e)=> txtColorChange(e)}/>

CodePudding user response:

What you need is an alpha channel to edit color opacity.

The react-color's documentation said that

"color accepts either a string of a hex color '#333' or a object of rgb or hsl values [...] Both rgb and hsl will also take a a: 1 value for alpha"

So instead of this:

color = {
    hex: '#f3f3f3',
}

You need to use an object like this:

color = {
    rgb: {
        r: 243,
        g: 243,
        b: 243,
        a: 1, //the opacity value is here
    },
}

Pay attention to convert red-blue-green hexadecimal values to decimal, on the example above the f3 become 243.

  • Related