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:
JavaScript
x
4
1
Route::get('/', function () {
2
return view('welcome');
3
});
4
This is my App.js content:
JavaScript
1
50
50
1
import React from 'react';
2
import { Switch, Route } from "react-router-dom";
3
import Signin from "../../containers/Signin";
4
import Signup from "../../containers/Signup";
5
import Error from "../../containers/Error";
6
import Courses from "../../containers/Courses";
7
import Course from "../../containers/Course";
8
import Quiz from "../../containers/Quiz";
9
import Header from "../Header";
10
import "./App.css";
11
import Library from "../../containers/Library";
12
import QuizResults from "../../containers/QuizResults";
13
import Main from "../Main";
14
import StudentsList from "../../containers/StudentsList";
15
16
17
function App()
18
{
19
return (
20
<div className="App">
21
22
<Header isLogged={false}/>
23
24
<Switch>
25
26
<Route exact path='/' component={Signin} />
27
<Route path='/signup' component={Signup} />
28
29
30
<Main>
31
<Route path='/courses' component={Courses} />
32
<Route path='/course/:id' component={Course} exact/>
33
<Route path='/quiz' component={Quiz} />
34
<Route path='/library' component={Library} />
35
<Route path='/quiz-results' component={QuizResults} />
36
<Route path='/students' component={StudentsList} />
37
</Main>
38
39
<Route component={Error} />
40
41
</Switch>
42
43
</div>
44
);
45
}
46
47
export default App;
48
49
50
app.js:
JavaScript
1
17
17
1
import React from 'react';
2
import ReactDOM from 'react-dom';
3
import { BrowserRouter } from 'react-router-dom';
4
import App from './components/App';
5
import './index.css';
6
7
8
ReactDOM.render(
9
<React.StrictMode>
10
<BrowserRouter>
11
<App />
12
</BrowserRouter>
13
</React.StrictMode>,
14
document.getElementById('root')
15
);
16
17
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
JavaScript
1
6
1
Route::any('{all}', function () {
2
return view('welcome');
3
})
4
->where('all', '^(?!api).*$')
5
->where('all', '^(?!storage).*$');
6
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