1
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?

Laravel側からReact側に値を渡す方法

Posted at

Laravelのcontroller → Blade → Reactコンポーネント、という経路で値を渡す典型パターンです。

data-* 属性経由で渡す

Controller → Blade

// Controller

public function show()
{
    $userName = 'Taro';
    $options = ['a', 'b', 'c'];

    return view('sample', [
        'userName' => $userName,
        'options'  => $options,
    ]);
}

Blade側(埋め込み)

// blade

{{-- resources/views/sample.blade.php --}}

<div
    id="my-react-root"
    data-username="{{ $userName }}"
    data-options='@json($options)'
></div>

@vite('resources/js/app.jsx')
  • シンプルな文字列はそのまま埋め込む。
  • 配列やオブジェクトは @json() で文字列化しておく。

React側(マウントと props 化)

// resources/js/app.jsx

import React from 'react';
import { createRoot } from 'react-dom/client';
import MyComponent from './components/MyComponent';

const el = document.getElementById('my-react-root');

if (el) {
  const username = el.dataset.username;
  const options = JSON.parse(el.dataset.options || '[]');

  createRoot(el).render(
    <MyComponent username={username} options={options} />
  );
}
// resources/js/components/MyComponent.jsx

export default function MyComponent({ username, options }) {
  return (
    <div>
      <p>{username} さんこんにちは</p>
      <ul>
        {options.map(o => <li key={o}>{o}</li>)}
      </ul>
    </div>
  );
}
1
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
1
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?