1.1.6 • Published 6 years ago
use-best-color v1.1.6
use-best-color 🎨
A React Hook to use the most accessible text color.
Compares a list of text color choices against an element's background color, and returns the color with the highest color contrast ratio.
WCAG (Web Content Accessibility Guidelines) ensure that content is accessible by everyone, regardless of disability or user device. To meet these standards, text and interactive elements should have a color contrast ratio of at least 4.5:1. This ensures that viewers who cannot see the full color spectrum are able to read the text.
Installation
$ npm i use-best-colorUsage
The useBestColor hook returns a tuple with two values:
- A
refobject to be passed to a DOM element- This element's background color will be used in the color contrast ratio calculation
A
bestColorobject containing:- A
colorvalue, ready to be used in a style - A
scorevalue representing the color contrast ratio between the text color and the background color, computed using the WCAG 2.0 guidelines for contrast accessibility
- A
By default,
useBestColorwill choose between whitergb(255, 255, 255)and blackrgb(0, 0, 0)
import React from 'react';
import useBestColor from 'use-best-color';
function SimpleExample() {
const [ref, bestColor] = useBestColor();
return (
<div>
<button ref={ref} style={{ color: bestColor.color }}>
Click Me!
</button>
</div>
);
}- Alternatively, you can pass
useBestColoran array of custom colors to choose from - Both RGB and Hex format are acceptable, and the
bestColor.colorvalue will be returned in the same format it was provided
import React from 'react';
import useBestColor from 'use-best-color';
function CustomExample() {
const [ref, bestColor] = useBestColor(['#CCCCCC', '#8C8C8C','#4D4D4D']);
return (
<div>
<button ref={ref} style={{ color: bestColor.color }}>
Click Me!
</button>
</div>
);
}