Skip to content

Instantly share code, notes, and snippets.

import React from 'react';
import { render, fireEvent, cleanup } from 'react-testing-library';
import { ColorToolContext } from '~/ColorToolContext';
import { updateHex } from '~/colorReducer';
import { HexInput } from '../HexInput';
describe('HexInput component', () => {
test('dispatch updated hex value when input changes', () => {
const testHex = '#abcef';
import { colorReducer, updateHex } from '../colorReducer';
describe('colorReducer', () => {
test('update color with valid hex', () => {
const initialState = {};
const testHex = '#abcdef';
const newState = colorReducer(initialState, updateHex(testHex));
expect(newState).toEqual({
@@ -13,7 +13,7 @@ export const ColorInput = () => {
}, []);
const onChange = ({ target: { value } }) => {
- dispatch({ type: 'UPDATE_HEX', payload: value })
+ dispatch(updateHex(value));
};
return show ? (
@@ -1,5 +1,5 @@
export const ColorInput = () => {
- const { hex, setHex, setRgba } = useContext(ColorToolContext);
+ const { hex, dispatch } = useContext(ColorToolContext);
const input = useRef(null);
const [show, setShow] = useState(true);
@@ -13,8 +13,7 @@ export const ColorInput = () => {
}, []);
@@ -1,20 +1,25 @@
-import React, { useState, createContext } from 'react';
+import React, { useReducer, createContext, Dispatch } from 'react';
import { HexInput } from '~/HexInput';
import { RgbaInput } from '~/RgbaInput';
+import { colorReducer } from '~/colorReducer';
interface ColorContextProps {
hex: string;
import parse from 'parse-color';
export function colorReducer(state = {}, action): ColorContextProps {
switch (action.type) {
case 'UPDATE_HEX': {
let nextState = { ...state };
const hexColor = action.payload;
if (/^#[a-f0-9]{6}$/i.test(hexColor)) {
const { hex, rgba } = parse(action.payload);
nextState = {
interface ColorContextProps {
hex: string;
rgba: number[];
-
- setHex: (value) => void;
- setRgba: (value) => void;
};
const ColorContext = createContext<ColorContextProps>({} as any);
@@ -10,7 +10,7 @@ export const ColorInput = () => {
useEffect(() => {
input.current.value = '!';
if ('!' === input.current.value) {
setShow(false);
}
- });
+ }, []);
const onChange = ({ target: { value } }) => {
export const ColorInput = () => {
const { hex, setHex, setRgba } = useContext(ColorToolContext);
const input = useRef(null);
const [show, setShow] = useState(true);
useEffect(() => {
input.current.value = '!';
// input[type=color] is not supported
if ('!' === input.current.value) {
@@ -1,6 +1,9 @@
-import React from 'react';
+import React, { useContext } from 'react';
+import { ColorToolContext } from '~/ColorToolAppContext';
+
+export const HexInput = () => {
+ const { hex, setHex, setRgba } = useContext(ColorToolContext);
-export const HexInput = ({ hex, setHex, setRgba }) => {
const onChange = ({ target: { value } }) => {