简体   繁体   中英

Single page application with Laravel-react

I am developing laravel-react js project for the first time. The reason for choosing react is to create single page application (SPA).

To setup my laravel project with react I am following this article

https://medium.com/@000kelvin/setting-up-laravel-and-react-js-the-right-way-using-user-authentication-1cfadf3194e

To create SPA, I am returning the same view for every fisrt level url by writing this line in my web.php

Route::view('/{path?}', 'index');

I have also created some route in my react component as follows

<Switch>
    <Route exact path="/" component={Home}/>
    <Route path="/login" component={Login}/>
    <Route path="/signup" component={Signup}/>
</Switch>

Now the problem is when change the url it will refresh the same view with different component.

I just wanted to render different component with respect to url without refreshing the whole page, otherwise what's the point of SPA.

can anybody show me the correct way of meeting my requirement or it is like this with Laravel and react.

Use the Link component supplied by your Router

A regular a tag by default will always cause a refresh.

You cannot just link to another page with a regular a tag, you must use the Link component from your router. If it's react router, here's the link

<Link
  to={{
    pathname: "/courses",
    search: "?sort=name",
    hash: "#the-hash",
    state: { fromDashboard: true }
  }}
/>

You can also pragmatically route with the useHistory hook. A more detailed version can be found here

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();
  // use history.push('/some/path') here
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM