1

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.

1 Answer 1

4

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
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.