I'm totally new to React.
i want to retrive data from a database using laravel ;
in my controller, I receive the data and send it in json form like this
public function index()
{
$data = DB::table('posts')->get();
return view('welcome')->withData(json_encode($data));
}
and its working perfectly.
Inside my home view, i called react like this.
<div id="example" data="{{ $data }}"></div>
<script src="js/app.js" ></script>
and this is the Example.js :
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
export default class Example extends Component
{
constructor(props)
{
super(props);
console.log(props.data);//[{"id":1,"name":"Laravel","created_at":null,"updated_at":null},{"id":2,"name":"Reacts Js","created_at":null,"updated_at":null}]
const json = JSON.parse(props.data);
var L = json.length;//2
for(var i =0 ; i < L ; i++)
{
console.log(json[i].name);//i==0 : Laravel
// i==1 : Reacts Js
}
}
render()
{
return (
<div className="container">
<div className="row justify-content-center">
<div className="col-md-8">
<div className="card">
<div className="card-header">Example Component</div>
for(var i =0 ; i < L ; i++)
{
<div>{json[i].name}</div>
}
<div className="card-body">I'm an example component!</div>
</div>
</div>
</div>
</div>
);
}
}
if (document.getElementById('example')) {
var data = document.getElementById(('example')).getAttribute('data');
ReactDOM.render(<Example data={data}/>, document.getElementById('example'));
}
in the browsers console i can see json[i].name perfectly ! BUT in the component i have this problem with the followinf error : Uncaught TypeError: Cannot read property 'name' of undefined.