Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
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>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

if you want to change the state of a specific key do it like this

SetselectedItems(oldState => ({...oldState, [type]:name}))

the spread operator ... get all object without what specific key you put the value

about 4 years ago · Juan Pablo Isaza Relatório

0

Just go:

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

Here's some info about the spread syntax I've used and you can read more about computed properties in this article.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda