You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React组件中正确使用Pickr原生JS颜色选择器库?

Fixing "TypeError: Unable to get property 'parentNode' of undefined or null reference" with Pickr in React

Hey there! Let's break down why this error is popping up and how to fix it.

What's Causing the Error?

When you initialize Pickr directly in the top level of your React component function, you're trying to create the color picker before React has rendered the .color-picker div to the DOM. Pickr can't find the element you're targeting, so it tries to access parentNode on a null value—hence the error.

The Solution: Use React's useEffect and useRef

We need to wait until the component's DOM has mounted before initializing Pickr, and clean up the instance when the component unmounts to avoid memory leaks. Here's the corrected code:

import React, { useEffect, useRef } from 'react';
import Pickr from '@simonwep/pickr';
import '@simonwep/pickr/dist/themes/classic.min.css';

export default function ColorPicker() {
  // Use ref to directly access the DOM element
  const pickrContainer = useRef(null);
  let pickrInstance = null;

  useEffect(() => {
    // Only initialize Pickr if the DOM element exists
    if (pickrContainer.current) {
      pickrInstance = Pickr.create({
        el: pickrContainer.current, // Target the ref instead of a class selector
        theme: 'classic',
        swatches: [
          'rgba(244, 67, 54, 1)',
          'rgba(233, 30, 99, 0.95)',
          'rgba(156, 39, 176, 0.9)',
          'rgba(103, 58, 183, 0.85)',
          'rgba(63, 81, 181, 0.8)',
          'rgba(33, 150, 243, 0.75)',
          'rgba(3, 169, 244, 0.7)',
          'rgba(0, 188, 212, 0.7)',
          'rgba(0, 150, 136, 0.75)',
          'rgba(76, 175, 80, 0.8)',
          'rgba(139, 195, 74, 0.85)',
          'rgba(205, 220, 57, 0.9)',
          'rgba(255, 235, 59, 0.95)',
          'rgba(255, 193, 7, 1)'
        ],
        components: {
          preview: true,
          opacity: true,
          hue: true,
          interaction: {
            hex: false,
            rgba: true,
            hsla: false,
            hsva: false,
            cmyk: false,
            input: true,
            clear: true,
            save: true
          }
        }
      });
    }

    // Cleanup: Destroy Pickr instance when component unmounts
    return () => {
      if (pickrInstance) {
        pickrInstance.destroy();
      }
    };
  }, []); // Empty dependency array ensures this runs once on mount

  return(
    <div ref={pickrContainer} className="color-picker"></div>
  )
}

Key Changes Explained:

  • useRef for DOM Access: Instead of using a class selector (.color-picker), we use a ref to directly reference the component's DOM element. This avoids conflicts if you use multiple ColorPicker components and is more reliable than querying the DOM.
  • useEffect for Post-Mount Initialization: The useEffect hook runs after the component has rendered to the DOM, so pickrContainer.current will be a valid element when we initialize Pickr. The empty dependency array ensures this logic only runs once when the component mounts.
  • Cleanup Function: We destroy the Pickr instance when the component unmounts to prevent memory leaks and leftover event listeners.

内容的提问来源于stack exchange,提问作者Ala Ben Aicha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:34:52