• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

262
Views
How can I pass useState value from one component to another component

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.

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

almost 3 years ago · Juan Pablo Isaza Report

0

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 :)

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error