1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactのpublicフォルダに配置したファイルを参照したい。

Posted at

実現したいこと

  • React(CRA)のビルドを挟まずにReactアプリ内から参照する値を手動で変更したい。
    (詳細: ホーム画面のインフォメーションが時折変更されるが、アプリのビルドが手間なのでビルドせずに変更したい。DBに入れるほどの情報ではない。Webサーバ上で直接ファイルを書き換えてインフォメーションを更新できるようにしたい。)

解決方法

  1. publicフォルダに対して、information.jsonのようにjsonファイルを配置
(root)
└── public/
    └── information.json
information.json
{
    "informations": [
        "お知らせ1",
        "お知らせ2",
        "お知らせ3"
    ]
}

2.参照したいコンポーネントでinformation.jsonをfetchする
=>アプリのルートパスを指定する必要があると思ってたんですが、単純にpublicディレクトリからの相対パスで良いみたいです。

const headers = { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
}
       
const info = fetch('information.json', { headers : headers})
      .then(res => res.json())
      .then(json => json.data?.informations)

こんな感じで無事にデータを取得することができました。
あとはJSONファイルを直接編集するなりなんなりして表示したい内容を切り替えることができます。

参考

1
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?