Laravel 5.5 render a React component in a blade view with data from the controller

后端 未结 3 1953
一生所求
一生所求 2021-02-09 11:30

My goals is to be able to do something like this in my blade view.

name }}\" />

But this doesn\'t render any

相关标签:
3条回答
  • 2021-02-09 12:24

    You can do it like this..

    @extends('layouts.app')
    
    @section('script')
        <script type="text/javascript">
            ReactDOM.render(<Example name="{{ $user->name }}"/>, document.getElementById('example'));
        </script>
    @endsection
    
    @section('content')
        <div id="example"></div>
    @endsection
    

    But better solution would be AJAX request to some controller that returns json data.

    Best solution for you will this laravel package laracasts/PHP-Vars-To-Js-Transformer

    0 讨论(0)
  • 2021-02-09 12:32

    This is perhaps a slightly cleaner solution than the others suggested. We don't need to specify each prop we pass in using this method either.

    In your blade file:

    <div id="react-component" data-foo='{{ $foo }}' data-bar='{{ $bar }}'>
    

    On a side note, if $foo is something that isn't JSON, e.g a Laravel Collection or an array, we can apply an additional method: $foo->toJson().

    In your component:

    if (document.getElementById('react-component')) {
    
        const component = document.getElementById('react-component');
        const props = Object.assign({}, component.dataset);
    
        ReactDOM.render(<ReactComponent {...props} />, component);
    }
    

    You'll then have access to all the props you pass in using the data attribute from your html. Just like any other react you can access your props inside of your component like: this.props.foo

    0 讨论(0)
  • 2021-02-09 12:33

    I do it like this eg. in index.blade.php

    <div id="main" data-user_name="{{$user->name}}" />
    

    Then in Main.js

    const Main = (props) => {
      return (
        <div>
          <Component {...props} />
       </div>
     );
    }
    
    if(document.getElementById('main')) {
      const el = document.getElementById('main')
      const props = Object.assign({}, el.dataset)
      ReactDOM.render(<Main {...props} />, el);
    }
    
    0 讨论(0)
提交回复
热议问题