Reputation: 55
My app was built using create-react-app. It all works fine once I'm using the app except when I click on the link from my portfolio website (on MAMP local host), it loads the custom 404 page instead of the Home component. When I load the app from npm run start it lands on the Home component first, I want it to do this on localhost and my live website too.
I've tried changing the "homepage" in package.json to "." but it still does the same thing.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Header from './components/layout/Header';
import NotFound from './components/layout/NotFound';
import Alert from './components/layout/Alert';
import Home from './components/content/Home';
import Movie from './components/content/movies/Movie';
import AlertState from './context/alert/AlertState';
import MovieState from './context/movies/MovieState';
const App = () => {
return (
<MovieState>`enter code here`
<AlertState>
<Router>
<Header text={"Movie App"}/>
<Alert />
<Switch>
<Route path='/' component={Home} />
<Route path='/movie/:title' component={Movie} />
<Route component={NotFound} />
</Switch>
</Router>
</AlertState>
</MovieState>
);
}
export default App
package.json
{
"name": "film_app",
"version": "0.1.0",
"homepage": ".",
"dependencies": {
"axios": "^0.19.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"react-scripts": "3.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
// Home.js
import React from 'react';
import Search from './Search';
import Movies from './movies/Movies';
const Home = () => {
return (
<>
<Search />
<Movies />
</>
)
}
export default Home
// NotFound.js
import React from 'react';
const NotFound = () => {
return (
<div>
<h1>
Page Not Found
<p className='lead' style={notFoundStyles}>
The page you are looking for does not exist
</p>
</h1>
</div>
)
}
const notFoundStyles = {
textAlign: 'center',
};
export default NotFound
There is no error message, it just shows the NotFound component rather than the Home component.
Upvotes: 2
Views: 1274
Reputation: 184
Add exact
flag to your Home
route, and path='/'
to the fallback route.
<Switch>
<Route path='/' exact={true} component={Home} />
<Route path='/movie/:title' component={Movie} />
<Route path='/' component={NotFound} />
</Switch>
Upvotes: 2