Home > Enterprise >  Laravel/React - Getting an array of data from controller to react component
Laravel/React - Getting an array of data from controller to react component

Time:03-07

My case:

I am combining Laravel (laravel/ui scaffolding) and React App. This is my first time trying this, and found myself stuck in getting data from BE to FE.

I Looks like I am getting the data, but my array of $testData is converted into a string When being logged from the Dataset of that element. I am not sure what I should do to have my array back to a json format instead.

the code:

A Controller sending my data:

    public function index()
    {
        $testData = [
            ["name" => "Lucy"],
            ["name" => "Kurt"],
            ["name" => "Emma"],
        ];

        return view('intern.index')->with('testData', $testData);
    }

I have my blade, loading a div with a certain id:

@extends('layouts.app')
@section('body')
    <div id="react-app" data-list={{ json_encode($testData) }} ></div>
@endsection

And my react component app.js that is rendered on the blade view:

function App( props ) {

    console.log(props.list)

    return (
        <div className="container">
            Hello World!
        </div>
    );
}

export default App;

if (document.getElementById('react-app')) {
    const thisElement = document.getElementById('react-app');
    let props = Object.assign({}, thisElement.dataset);
    console.log(props)
    /* The restult I am getting from that log:
    {
      list: "{{\"name\":\"Lucy\"},{\"name\":\"Kurt\"},{\"name\":\"Emma\"}}"
    }
    */
    ReactDOM.render(<App list={props.list} />, thisElement);
}

CodePudding user response:

Update:

The solution was to simply parse the result back.

if (document.getElementById('react-app')) {
    const thisElement = document.getElementById('react-app');
    let props = Object.assign({}, thisElement.dataset);
    console.log(props)
    /* The restult I am getting from that log:
    {
      list: "{{\"name\":\"Lucy\"},{\"name\":\"Kurt\"},{\"name\":\"Emma\"}}"
    }
    */
    ReactDOM.render(<App list={JSON.parse(props.list)} />, thisElement);
}
  • Related