One of this way you pass data from laravel controller to react component.
A React Component interact with view id element document.getElementById('example')
on your laravel viewpage.
Your Laravel Controller like.
class HomeController extends Controller
{
public function index(){
$data = [
'john', 'doe'
];
return view('welcome')->with('data', json_encode($data));
}
}
Make sure you passing data controller to view as json. Your Blade View
..
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div id="example" data='{{ $data }}'></div>
<script src="js/app.js"></script>
</body>
Your Example Component in reources/assets/js/components/Example.js like
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Example extends Component {
constructor(props){
super(props);
console.log('data from component', JSON.parse(this.props.data));
}
render() {
return (
<div className="container">
.....
</div>
);
}
}
if (document.getElementById('example')) {
var data = document.getElementById('example').getAttribute('data');
ReactDOM.render(<Example data={data} />, document.getElementById('example'));
}
Make sure, when you change of Example.js Component code then you must run npm run dev
command on your command prompt.
@extends('layouts.app') @section('content') <example-component datas={{ $datas }}></example-component> @endsection
– Ervin