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

251
Visualizações
Cannot read properties of undefined (reading 'some_props')

I have a problem with React conditional rendering. I want to render a specific prop if it's set so first I'm checking if the prop exists and then outputing it otherwise output 0, but React has a problem checking if the variable exists when it's undefined at first load...

number:
    props.dashboardCards[0].items.thisMonth[0].itemTitle
      ? props.dashboardCards[0].items.thisMonth[0].itemTitle
      : 0,

This is my code I want to create an object with number field and in that field I want to set this prop if it exists otherwise 0. And React keeps giving me error:

TypeError: Cannot read properties of undefined (reading 'itemTitle')

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

thisMonth is probably empty or undefined. You can use optional chaining to solve this:

number: props.dashboardCards[0]?.items?.thisMonth[0]?.itemTitle ?? 0,

Now if props.dashboardCards[0].items.thisMonth[0].itemTitle exists number will be the value of it, or it'll be 0.

The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Learn more about optional chaining from here.

about 4 years ago · Juan Pablo Isaza Relatório

0

The error says that there is no itemTitle in the thisMonth array.

If it's coming from the API, you need to wait to get it. You can simply check the props by the console.log(props) and check it before using dot notation to get the itemTitle.

You can also check for a value with optional chaining ? :

props?.dashboardCards[0]?.items?.thisMonth[0]?.itemTitle

It means:

if(props){
  if(dashboardCards[0]){
    if(items){
      if(thisMonth[0]){
        props.dashboardCards[0].items.thisMonth[0].itemTitle
      }
    }
  }
}
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