LoginSignup
0
0

More than 1 year has passed since last update.

CakePHPので変数を渡しているViewの上に展開させているReactでその値を拾う

Posted at

今までフロントから api でデータフェッチするやり方しか知らなかったのでこのような方法もあるというメモ

  • data属性を使う
    cakephp の View ファイルでは以下のように data 属性に入れておく
View/index.ctp
<div class="hoge" data-object-for-modal='<?= json_encode($object) ?>'></div>

以下 React の jsx | tsx ファイル

components/index.tsx
// DOM を取得
const HOGE = document.querySelector('.hoge') as HTMLElement 
// データ属性に埋め込まれてる値を取得
const { objectForModal } = HOGE.dataset;
// パースする
cosnt object = objectForModal && objectForModal !== '[]' ? JSON.parse(objectForModal) : null

cakephp の view で data 属性に渡す値が動的に変化する値で、 null が渡されることがある場合はデータ属性から値を取得する時にエラーとなるので注意。

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