1

it turns out that I'm having a small problem that I find very strange that is not solved with the OR operator (||).

In the following code, you can see that I am sending a

 return (
      <div>
        {listShow.map(i => (
          <Link to={`/noticias/detalle/${i.categoria.id/${i.id}`} key={i.id}>
            <h3>{i.titulo}</h3>
            <img
              alt={i.titulo}
              src={process.env.REACT_APP_IMG_BASE + i.imagen_intro}
              width={500}
            />
          </Link>
        ))}
    );

However, at some point, "i.categoria.id" becomes null and this generates an error that says:

"TypeError: Can not read property 'id' of null"

Then, I tried this:

 return (
      <div>
        {listShow.map(i => (
          <Link to={`/noticias/detalle/${i.categoria.id/${i.id} || 'WithoutCat'`} key={i.id}>
            <h3>{i.titulo}</h3>
            <img
              alt={i.titulo}
              src={process.env.REACT_APP_IMG_BASE + i.imagen_intro}
              width={500}
            />
          </Link>
        ))}
    );

I would like to know how to solve this, since it seems strange to me that I take the value when I am putting the operator ||

Thank you!

1
  • Be aware that if categoria.id is undefined and you set "WithoutCat" as a fallback, you might end up with dead links. Commented Feb 19, 2019 at 14:21

1 Answer 1

1

Categoria is null and you are trying to access a property of it, check before if it is null, try this instead:

<Link to={i.categoria && i.categoria.id ? `/noticias/detalle/${i.categoria.id}/${i.id}` : 'WithoutCat'} key={i.id}>

Hope it helps! :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, it works perfect! I will give you the best answer in case someone else has the same problem :)
My pleasure, glad it helped :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.