0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

学習87日目

Posted at

テーマ

reactで.envからの環境変数を呼び出す

前提

  • ruby on rails x react で実装中
  • google maps api導入済
  • .envにapi keyを記述している
  • 該当部分以外の記述は省略

内容

方法1:カスタムデータ属性を使う

view上にapi keyを参照するカスタムデータ属性を作成し、それをjs側で呼び出す。

.env

GOOGLE_API_KEY = 'xxxxxxxxxxxxxxxxx'

app/views/hoges/index.html.erb

    <div id='map_area' style='width:500px;height:500px;' data-api-key="<%=ENV['GOOGLE_API_KEY'] %>"></div>

app/javascript/packs/application.js

const mapArea = document.getElementById('map_area')
const apiKey = mapArea.dataset.apiKey

※「data-api-key」(スネークケース)で記述した場合、jsでの呼び出しは「dataset.apiKey」(キャメルケース)であることに注意

方法2:gem 'gon' を使う

controllerでgonを用いてapi keyをセットし、それをjs側で呼び出す。

.env

GOOGLE_API_KEY = 'xxxxxxxxxxxxxxxxx'

app/views/hoges/index.html.erb

    <div id='map_area' style='width:500px;height:500px;'></div>

app/controllers/hoges_controller.rb

def index
  gon.apiKey = ENV['GOOGLE_API_KEY']
end

`app/javascript/packs/application.js`

const apiKey = gon.apiKey


# コメント
どちらの方法でもブラウザ上でapi keyを参照可能なので、google cloud console側で制御するしかなさそう。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?