Returning a string value after array.find() is throwing a Objects are not valid as a React child

Viewed 232

In code snippet below, console.log(el.distance) is equal to a string. For one reason or the other, if I try to return el.distance react keeps throwing me the classic:

Error: Objects are not valid as a React child (found: object with keys {item, distance}). If you meant to render a collection of children, use an array instead.

  return evtsFiltered?.map((item) => {
    return (
      <div>
        Distance:
        {distance?.find((el) => {
          if (el.item === item._id) console.log(el.distance)
        })}
      </div>
    )
  })

How can?

I also tried putting it between html tags like so

return evtsFiltered?.map((item) => {
    return (
      <div>
        Distance:
        {distance?.find((el) => {
          if (el.item === item._id) return <p> {el.distance} </p>
        })}
      </div>
    )
  })

Nothing works, please help!

2 Answers

.find returns an object from an array that satisfy the testing function. Result of find can't simply be a string if the array is of type objects.

You should be doing something like this

{distance?.find((el) => el.item === item._id)?.distance}

As you can see here the function .find return the first value found by the callback. It is differente from a map, that will return anything you return in the callback funcion Instead of this:

    {distance?.find((el) => {
      if (el.item === item._id) return <p> {el.distance} </p>
    })}

You can try this:

<p>
   {distance?.find((el) => {
      if (el.item === item._id) return {el.distance} 
    })}
</p>
Related