1
1

Error: Objects are not valid as a React child の解決方法

Last updated at Posted at 2024-08-03

はじめに

Reactの勉強をしているときに、オブジェクトをmapで表示しようとした際にエラーがでました。
初歩的な部分ですが、解決策をまとめておきたいと思います。

事象

以下のようなコードを実行した際に、mapの中の{ record }の部分でエラーが発生しました。

export const App = () =>{
  const records = [
    { name: "山田太郎", age: 13},
    { name: "山田次郎", age: 12},
  ]
  return (
    <>
      { records.map((record) => (
        <div>
          <div>{ record }</div>
        </div>
      ))}
    </>
  )
}

発生したエラー

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

原因

オブジェクト型を表示しようとした際に発生するエラーでした。
Reactではオブジェクト型を直接表示することはできないようです。

解決方法

オブジェクト型のプロパティを直接指定する

{ record.name }

JSONの文字列に変換する

{ JSON.stringify(record) }

終わりに

オブジェクト型を扱う際には注意していこうと思います。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1