user2442241
user2442241

Reputation: 975

Laravel routes and blade templating with reactjs

Is there some way I can use blade type syntax with React to handle my Laravel routes? Let's say I have something like the following:

<div class="card">
    <a href="{{ route('account.show', $user->slug) }}">Go to your account</a>
</div>

If I try to make this into a Reactjs component, clearly the blade type syntax won't work.

I have looked into React Router, but don't exactly know how it would fit into my application, or if it is even necessary for me to use (I'd much rather use plain Laravel routes).

Upvotes: 1

Views: 2978

Answers (1)

Tobia
Tobia

Reputation: 18831

React code is not executed by Laravel, but by the user's browser. So when the time comes to generate that href, inside the user's browser, the code does not have any more access to Laravel or Blade tools.

What you can do is to pass all the info you need to your React app, beforehand, when you use blade to generate the top level React invocation:

<script>
    React.render(
        MyApp({
            accountShow: "{{ route('account.show', $user->slug) }}",
            //etc.
        }),
        document.getElementById('myContainer')
    )
</script>

So then in your React app you can use those properties and pass them down to inner components, e.g:

<CardLink href={this.props.accountShow}>
    Go to your account
</CardLink>

Upvotes: 2

Related Questions