I use React Router and Laravel. When I navigate throught Link elements all OK, but when I change browser address line to manually show another component Laravel shows it defalt 404 page.
This is default web.php content, in welcome.blade.php I inlcude js/app.js file:
Route::get('/', function () { return view('welcome'); });
This is my App.js content:
import React from 'react'; import { Switch, Route } from "react-router-dom"; import Signin from "../../containers/Signin"; import Signup from "../../containers/Signup"; import Error from "../../containers/Error"; import Courses from "../../containers/Courses"; import Course from "../../containers/Course"; import Quiz from "../../containers/Quiz"; import Header from "../Header"; import "./App.css"; import Library from "../../containers/Library"; import QuizResults from "../../containers/QuizResults"; import Main from "../Main"; import StudentsList from "../../containers/StudentsList"; function App() { return ( <div className="App"> <Header isLogged={false}/> <Switch> <Route exact path='/' component={Signin} /> <Route path='/signup' component={Signup} /> <Main> <Route path='/courses' component={Courses} /> <Route path='/course/:id' component={Course} exact/> <Route path='/quiz' component={Quiz} /> <Route path='/library' component={Library} /> <Route path='/quiz-results' component={QuizResults} /> <Route path='/students' component={StudentsList} /> </Main> <Route component={Error} /> </Switch> </div> ); } export default App;
app.js:
import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter } from 'react-router-dom'; import App from './components/App'; import './index.css'; ReactDOM.render( <React.StrictMode> <BrowserRouter> <App /> </BrowserRouter> </React.StrictMode>, document.getElementById('root') );
So, how to force React Router react on direct browser address line change?
Advertisement
Answer
as your working with SPA so you need to configure your web.php
like this
Route::any('{all}', function () { return view('welcome'); }) ->where('all', '^(?!api).*$') ->where('all', '^(?!storage).*$');
then react router will catch all routes
and here api
and storage
routes is exclude from catch so you can use storage files and api to make call api