如何在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:
useReffor 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 multipleColorPickercomponents and is more reliable than querying the DOM.useEffectfor Post-Mount Initialization: TheuseEffecthook runs after the component has rendered to the DOM, sopickrContainer.currentwill 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
相关产品推荐
相关产品推荐

