3 - Color Picker with Hex Code Display
Description
Create a React application that displays a color picker. The color picker should allow users to select a color and display the corresponding hex code.
Algorithm
Initialize a state variable to store the selected color's hex code.
Render a color picker component that allows users to select a color.
Update the state variable when a color is selected.
Render the selected color's hex code.
Classes
ColorPicker
: A React component that manages the selected color and renders the color picker and hex code display.
Code
import React, { useState } from 'react';
function ColorPicker() {
const [selectedColor, setSelectedColor] = useState('#ffffff');
const handleColorChange = (event) => {
setSelectedColor(event.target.value);
};
return (
<div>
<input
type="color"
value={selectedColor}
onChange={handleColorChange}
/>
<p>Selected Color: {selectedColor}</p>
</div>
);
}
export default ColorPicker;
Explanation
The code defines a ColorPicker
component that utilizes the useState
hook to initialize a state variable selectedColor
to a default hex code. A color picker input is rendered, allowing users to select a color. When a color is selected, the handleColorChange
function updates the selectedColor
state variable. The selected color's hex code is then rendered below the color picker.
Possible Future Enhancements
Add a color palette to display recently selected colors.
Implement a color preview feature to display the selected color as a swatch.
Use a library like TinyColor to convert the hex code to other color formats (e.g., RGB, HSL).
Integrate with a design app to allow users to apply the selected color to a design project.
Last updated