Adding a Color Picker to ReactQuill

React, ReactQuill, ColorPicker

It was too much research for me to add a Color Picker to my Text Editor until I decided to stick to basics.

A simple input tag and React.useRef made it work just on the first go.

Implementation

ColorPicker.js

import React, { useState } from 'react';
import 'react-quill/dist/quill.snow.css';

const ColorPicker = ({quillRef}) => {
  const [color, setColor] = useState('#000000');

  const handleChangeColor = (e) => {
    setColor(e.target.value);
  };

  const handleApplyColor = () => {
    const selection = quillRef.current.getEditor().getSelection();
    if (selection) {
      quillRef.current.getEditor().format('color', color);
    }
  };

  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <input
        type="color"
        value={color}
        onChange={handleChangeColor}
        style={{height:'1vh',aspectRatio:1}}
      />
      <button onClick={handleApplyColor}>Set</button>
    </div>
  );
};

export default ColorPicker;

Easy, Right. Now we just need to add it to the toolbar we made in our earlier blog of this series. For that, we need to use it in our Editor.js which renders the ReactQuill component.

We can do that by adding a useRef, adding it to ReactQuill, and then sending this ref to our ColorPicker as a prop.

Editor.js

import React,{useRef}  from "react";
import 'quill/dist/quill.snow.css'
import ReactQuill from 'react-quill'
import Toolbar, { modules, formats, styles } from "./ToolBar";
import "react-quill/dist/quill.core.css";
import './styles.css';
import ColorPicker from "./ColorPicker";


const TextEditorQuill = (props) => {
    const [state, setState] = React.useState({ value: null });
    const handleChange = (value) => {
        setState({ value });
    };
    const quillRef = useRef();

    return (
        <div className="w3-card">
          <Toolbar />
          <ColorPicker quillRef={props.quillRef} /> 
          <ReactQuill
            ref={quillRef}
            theme="snow"
            value={state.value}
            onChange={handleChange}
            placeholder={"Start Here..."}
            modules={modules}
            formats={formats}
          />
        </div>
      );

}
export default TextEditor;

Now keep it simple like that or add it to toolbar.js and then render, it's your choice

Results

See you all. Have a Nice Day ;)