Reputation: 1021
I have a react BrowserRouter with the following configuration.
<BrowserRouter>
<div>
<Switch>
<Route path={`/`} component={Home} exact/>
<Route path={`/about`} render={(props) => <About {...props}/>} exact/>
<Route path={`/products/:id/:slug`} render={(props) => <Products {...props}/>} exact/>
</Switch>
</div>
In the About Page there are products with the following tag. If I click a link, the url changes and Product page is getting rendered correctly.
<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>
But when I directly Land to Product page using the exact URL. rendering won't work.
e.g localhost:3000/products/123/books
Any idea what's causing the issue?
Upvotes: 1
Views: 5248
Reputation: 338
Based on your description, I assume that it worked fine when you enter homepage in address bar, But when you refreshed the page or enter any other pages, you got some errors.
Here is the solution:
Firstly: you need set the historyApiFallback: true
in webpack.config.js
,
devServer: {
...
historyApiFallback: true,
}
Secondly:
set publicPath
of output field in webpack.config.js
,:
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/',
},
I think this answer would help you: React-router urls don't work when refreshing or writing manually
Upvotes: 2
Reputation: 1
From what i understand this code :
<Link to={'/products/' + product.id + '/' + product.slug>{product.name }</Link>
will generate a syntax error because its missing a closing parenthesis.
This should be like this :
<Link to={'/products/' + product.id + '/' + product.slug}>{product.name }</Link>
Note the "}" at the end of product.slug
Upvotes: 0
Reputation: 706
Based on your input, I'd say this is a syntax error or an issue with a componentDidMount/useEffect in your component.
I think I spot the syntax error though: "product.slug>"
You should remove the ">" after slug and you'll probably be good to go!
Upvotes: 0
Reputation: 8418
To make 'client-side, virtual' routes working from any url you need a server side support - f.e. apache mod-rewrite.
Already ansered here
Upvotes: 0
Reputation: 58
In your product component use
if component is statefull component
this.props.match.params.id for id = 123
this.props.match.params.slug for slug = books
if component is stateless component then you need to use "withRouter" to make above line available import { withRouter } from "react-router";
and wrap your function in this method
const MyComponent = () => {} export default withRouter(MyComponent)
It should work!!!
Upvotes: 0
Reputation: 384
I believe you issue is you get error CANNOT GET when you tru the direct url. Try setting historyApiFallback: true
in your webpack.config.js
Upvotes: 0