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

131
Visualizações
Check if array undefined in React component

I have a code in React component that renders match name. But sometimes current match have emty object and I can't pass this issue. Component code:

import React from 'react'
import {Link} from 'react-router-dom'

    export const MatchList  = ({ links }) => {
      if (!links.length) {
        return <p className="center">Матчей пока нет</p>
      }
    
      return (
        <table>
          <thead>
          <tr><th><a href="/add">Добавить ссылку</a></th></tr>
          <tr>
            <th>link</th>
            <th>Открыть</th>
          </tr>
          </thead>
    
          <tbody>
          { links.map((link, index) => {
            return (
              link.dataInfo1param1.length > 0 ?
              <tr key={link._id}>
                <td>{link.url}</td>
                <td>
                  Name: { link.dataInfo1param1[0][0]['odddTitle'] } <Link to={`/match/${link._id}`}>Открыть</Link>
                </td>
              </tr>
              :
              <tr key={link._id}>
                <td>{link.url}</td>
                <td>
                  <Link to={`/match/${link._id}`}>Открыть</Link>
                </td>
              </tr>
            )
          }) }
          </tbody>
        </table>
      )
    }

When link.dataInfo1param1 has an empty value I always get an error

× TypeError: Cannot read properties of undefined (reading 'length')

How I can check that this value do not exist or empty? Thanks

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

0

Check out optional chaining.

link.dataInfo1param1?.length > 0
about 4 years ago · Juan Pablo Isaza Relatório

0

you can use ternary operator for this check as below.

       <td>
          Name: { link.dataInfo1param1?link.dataInfo1param1[0][0]['odddTitle']:null } <Link to={`/match/${link._id}`}>Открыть</Link>
        </td>
about 4 years ago · Juan Pablo Isaza Relatório

0

the simplest solution would be link.dataInfo1param1 && link.dataInfo1param1.length > 0

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