6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【忘備録】オブジェクトや配列を別ファイルで管理する

Posted at

はじめに

Reactの個人開発(学習)でオブジェクトや配列を別ファイルで書きたいときに毎回書き方を忘れてしまうので、書きます。

const records = [
  { title: "ダミーテキスト1", time: 1 },
  { title: "ダミーテキスト2", time: 3 },
  { title: "ダミーテキスト3", time: 5 },
];

問題

 ReactでもJavaScriptと同じく、同じファイル上でオブジェクトや配列を宣言すれば問題なく使用できるが、コードが長くなると見づらいのと使い回しなどもしづらいので別ファイルで管理したい!

解決方法

①オブジェクトや配列用のファイルを作成する。今回は、src配下にdataディレクトリを作成しその中にjsファイルを作成。

スクリーンショット 2025-07-09 0.30.40.png

②src/data/recordsData.json ファイルに先ほどのオブジェクトを宣言し、最後にexportするオブジェクト追記します。

[
  {
    "title": "勉強の記録1",
    "time": 1
  },
  {
    "title": "勉強の記録2",
    "time": 3
  },
  {
    "title": "勉強の記録3",
    "time": 5
  }
]

③最後、使用するファイルにインポート文を記述する。

import records from "./data/recordsData.json";

こうすれば使えるようになります。recordsはデータを代入する変数なので好きな変数にして下さい。意外と簡単だけどしばらく書いてないと忘れちゃう。

おわりに

const recordsData = records;

このように記述すれば定数として宣言し直すこともできます。

今回はJSONで作りましたが、JSでも作れます。ただ一般的にはJSONで作ることが多いのではないかなと思います。TypeScriptを使うと型宣言を必要になるので、型宣言用のファイルも作ったりします。

6
3
4

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
6
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?