jaames / iro.js

🎨 Modular color picker widget for JavaScript, with support for a bunch of color formats
https://iro.js.org
Mozilla Public License 2.0
1.3k stars 81 forks source link

reset React state #195

Closed Abd3lwahab closed 3 years ago

Abd3lwahab commented 3 years ago

I am trying to use iro.js with react functional component and it works fine when I use an individual state for color, but when I try to use it with the state that shares another data it's reset the state every time color change

// ColorPicker.js

import React, { useEffect, useRef } from 'react'
import iro from '@jaames/iro'

const ColorPicker = ({ color, onChange }) => {
  const ref = useRef()
  const colorPicker = useRef()
  useEffect(() => {
    const cp = (colorPicker.current = new iro.ColorPicker(ref.current, {
      color,
    }))
    cp.on('color:change', (color) => onChange(color.hexString))
  }, [])
  return <div ref={ref} />
}

export default ColorPicker
//App.js

import { useState } from 'react'
import ColorPicker from './components/ColorPicker'
import Radio from './components/Radio'

const App = () => {
  const [state, setstate] = useState({
    color: '#ffffff',
    level: 'OFF',
  })

  return (
    <div>
      <ColorPicker
        color={state.color}
        onChange={(color) => setstate({ ...state, color: color })}
      />
      <Radio
        selected={state.level}
        options={['OFF', '25%', '50%', '75%', '100%']}
        changeHandler={(level) => setstate({ ...state, level: level })}
      />
    </div>
  )
}

export default App 

so when I make a change with the 'Radio' component it works but after I change the color the value of Radio change back to the initial state again, and color value updated

jaames commented 3 years ago

I'm struggling to understand the question, but this seems like an issue with how you're using React, not with iro.js