Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

change Usestate Object with prop

i am trying to change the value of items in the selectedItems Object.
but the changeSelectedItems function always sets the name of the variable to type instead of the value of the property ‘type’.
How do i use the type property as the name for the value?

  const [selectedItems, SetselectedItems] = useState({
    shirt:'none',
    pants:'none',
    hat:'none',
  })

  const changeSelectedItems = (name,type) =>{
    SetselectedItems({type:name})
  }

<div onClick={() =>changeSelectedItems('blue shirt','shirt')}> blue shirt </div>
<div onClick={() =>changeSelectedItems('jeans','pants')}> jeans </div>
<div onClick={() =>changeSelectedItems('tophat','hat')}> tophat </div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

it should be

  const [selectedItems, SetselectedItems] = useState({
    shirt:'none',
    pants:'none',
    hat:'none',
  })

  const changeSelectedItems = (name,type) =>{
    SetselectedItems(selected => ({...selected, [type]:name}))
  }

<div onClick={() =>changeSelectedItems('blue shirt','shirt')}> blue shirt </div>
<div onClick={() =>changeSelectedItems('jeans','pants')}> jeans </div>
<div onClick={() =>changeSelectedItems('tophat','hat')}> tophat </div>

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading