Home > Blockchain >  How can I pass useState value from one component to another component
How can I pass useState value from one component to another component

Time:01-03

I have 2 components editor.js and toolbar.js, I want to pass activeTool value from Toolbar.js to editor.js. I am expecting it to be updated after each click.

Editor.js

import Toolbar from './Toolbar.js'

export default function Editor() {

 const [canvas, setCanvas] = useState()

// I want current activeTool from Toolbar.js to use here -------------------

  useEffect(() => {
    if (!canvas) return

    if (activeTool !== 'select') canvas.discardActiveObject().requestRenderAll()

    handleDrawingModes(canvas, activeTool)
  }, [canvas, activeTool])

//-------------------------------------------------------------------------

return (
    <>
    <Toolbar />
    <Canvas canvas={canvas}/>
    </>
  )
}

Toolbar.js

const tools = [
  { name: 'Select',    func: 'select',     icon: BsCursor         },
  { name: 'Pencil',    func: 'draw',       icon: BsPencil         },
  { name: 'Eraser',    func: 'erase',      icon: BiEraser         },
]

export default function Toolbar() { 

  const [activeTool, setActiveTool] = useState('select')

return (

 <Menu defaultSelectedKeys={['Select']}  >
  {tools.map((item) => (
    <Menu.Item key={item.name} onClick={ () => setActiveTool(`${item.func}`) }> 
         <item.icon />
    </Menu.Item>
  ))}
  </Menu>
   )
}

Any help would be appreciated.

CodePudding user response:

There are various methods to achieve it, from which you can pick the approach best fits your project.

Lift the state

// Refactor the Toolbar,
//  so it will only take care about display,
//  while state management will be the job of Editor.

export default function Toolbar(props) { 

return (

 <Menu defaultSelectedKeys={['Select']}  >
  {tools.map((item) => (
    <Menu.Item key={item.name} onClick={ () => props.onSelectedItemChange(item.func) }> 
         <item.icon />
    </Menu.Item>
  ))}
  </Menu>
   )
}

State store

You can use react context or state management libraries to build a global or local state store to handle this.

CodePudding user response:

Above answer is the best. But you can in addition to that also use "useRef"

<Toolbar ref={myRef} />

Then access the state via myRef.current.state.

But the answer from @Yan is the way to go :)

  • Related