LoginSignup
2

More than 1 year has passed since last update.

【Laravel】bladeファイルでReact側に変数を渡す

Last updated at Posted at 2021-10-14

はじめに

Laravelで一部分をReactでSPA化した際、APIを使うまでもなさそうな変数をグローバル変数として渡していました。
一応、備忘録として残します。

実装

script内でconst access_token = "{{ $access_token }}"のように値を渡します。

@section('main')
    <link href="{{ asset('/css/app.css') }}" rel="stylesheet" type="text/css">
    <script>
        const access_token = "{{ $access_token }}"
        const api_url = "{{ url('/graphql') }}";
        const app_store_url = "{{ env('APP_STORE_URL') }}"
        const pet_age = @json(config('define.pet.age'));
    </script>
    <div id="app"></div>
    <script src="{{asset('/js/app.js')}}"></script>
@stop

以下のような連想配列(および配列)を渡す際には、@jsonでJSONに変換して渡します。

pet.php
<?php
return [
    'age' => [
        'dog' => 5,
        'cat' => 10,
        'bird' => 8,
    ]
];

React側で変数を呼び出す際、TypeScriptを使っているとWarningCan't find name ~がでるので、新しく変数を用意して// @ts-ignoreをつけてあげます。

index.ts
const Component = () => {
  // @ts-ignore
  const petAge = pet_age
  ...
}

参考資料

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
2