I'm using react-router with routes parameter:
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
indexRoute: { onEnter: (nextState, replace) => replace('/new-url') }
};
Here is the Router jsx part:
<Router
history={hashHistory}
routes={rootRoute}>
</Router>
The indexRoute is the line I was trying to add to make the redirect but it doesn't work.
You need to add path: '/' to your rootRoute.
Related
Starting my app on --> http://localhost:8000
I created a component called "NavBar", and in this component I created a Link to "/home".
In "/home" Im just rendering the following text --> "Test React Router Dom"
On "NavBar" component, clicking on Link to "/home" it work, but when I try to refresh the page on "/home" or just typing URL: "http://localhost:8000/home" it fails.
"react": "^18.2.0"
"react-dom": "^18.2.0"
"react-router-dom": "^6.4.1"
"typescript": "^4.8.4",
Error -->
// App.tsx
import { NavBar } from './components/NavBar'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
export const App = () => {
return (
<div>
<Router>
<Routes>
<Route path="/" element={<NavBar />} />
<Route path="/home" element={<h1>Test React Router Dom</h1>} />
</Routes>
</Router>
</div>
)
}
// NavBar.tsx
import './navBar.style.scss'
import { Link } from 'react-router-dom'
export const NavBar = () => {
return (
<>
<Link to={'/home'}>Link to Home</Link>
</>
)
}
//index.tsx
import { createRoot } from 'react-dom/client'
import { App } from './App'
const container = document.getElementById('root') as HTMLElement
const root = createRoot(container)
root.render(<App />)
This will be because your server needs to support HTML5 push state. When you navigate by clicking a link that's using the HTML5 history API (which react-router uses under the hood), its only changing the URL in the address bar -- it doesnt actually try to fetch that page from the server. However when you refresh or hit the URL from the outside of the site, the browser will simply try to load that URL from the server -- there is no client side code even loaded to use the history API.
Your server needs a wildcard route configured such that any and all paths serve your index.html. Then, your JS etc will load, read from the URL, and display the desired page.
If it's an express server you'd need something like this -- but the exact details really depend on your server technology and setup:
app.get('*', function(request, response) {
response.sendfile(__dirname + '/public/index.html');
});
I found a solution, Im using WebPack and I added the following config on Development mode -->
devServer: {
historyApiFallback: true,
}
But I don't understand how "historyApiFallback" works.
Will I need to add some another configuration on my Production mode to prevent the same error?
// webpack.prod.js
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
module.exports = {
mode: 'production',
devtool: 'source-map',
devServer: {
historyApiFallback: true,
},
optimization: {
minimizer: [new CssMinimizerPlugin(), new TerserPlugin()],
},
plugins: [],
}
const routes = [{
path: '/',
element: <Layout/>,
children: [
{
path: '/home',
element: <Home/>,
}
]
}]
I hava two components, Home and Layout.
I would like to redirect my url for e.g to '/home' when I only write /, but here is a problem:Layout can't bind element.
{
path: '/',
element: <Navigate to="/home"/>
}
or use index router, but I can't set path = '/home', Layout and Home use same url /, I don't want this.
I use React router version "react-router-dom": "^6.3.0", So how can I set default router?
As im new to Reactjs it is hard for me to explain this, but I am trying to define all pages(components, routes and more) on a different page (routes.js) and looping this on the app.js page in order to build all pages/routes. But the imports of the pages are not working because I didn't defined them on the same page.
When I 'am not using the foreach the pages will load.
//app.js
import RC from './constants/Routes';
import {Page1,Page2,Page3} from "./components/pages";// not used here but set in route.js
<Switch>
{Object.keys(RC).forEach(key=>{
<Route path={RC[key].route} component={RC[key].component}/>
})}
</Switch>
//routes.js
export default Object.freeze({
PAGE1: {
route: '/page1',
component: 'Page1'
},
PAGE2: {
route: '/page2',
component: 'Page2'
},
PAGE3: {
route: '/page3',
component: 'Page3'
},
});
const routes = [
{ component: Root,
routes: [
{ path: '/',
exact: true,
component: Home
},
{ path: '/child/:id',
component: Child,
routes: [
{ path: '/child/:id/grand-child',
component: GrandChild
}
]
}
]
}
]
routes.config.js export routes object using in renderRoutes method which is exported by react-router-config
when I start the app and access the url localhost:3000 the Home component will be rendered .
If access localhost:3000/child the request is 404.
If access localhost:3000/#/child but it render Home component instead of Child component
In the development mode I know can add devServer:{historyApiFallback:true}, but should I do in the production mode ?
If using HashRouter it works well.
So how can I using the BrowserRouter?
Try this:
Step 1: Wrap your <App /> inside <BrowserRouter />
Step 2: <Router path="/child" component={Child} />
Step 3: Point this router using <Link to="/CHILD>Child</Link>"
was experimenting with react and was replacing hashHistory with browserHostory. The application is a static application running on apache server and not on node. Have used the libraries for React, Reaact-dom, ReactRouter and created js pages for various routes. The replaced code doesn't seem working and on console got the message Uncaught ReferenceError: browserHistory is not defined . Below is he code for the same ? I want to replace hash history with browserHistory.
<script type="text/javascript">
var destination = document.querySelector("#container");
var { Router, Route, IndexRoute, IndexLink, Link } = ReactRouter;
ReactDOM.render(React.createElement(Router,{ history : browserHistory },React.createElement(
Route,{ path: "/", component: App },
React.createElement(IndexRoute, { component: Home }),
React.createElement(Route, { path: "/stuff", component: Stuff }),
React.createElement(Route, { path: "/contact", component: Contact }),
React.createElement(Route, { path: "/event", component: Event }),
React.createElement(Route, { path: "/search", component: Search }),
React.createElement(Route, { path: "/fetch", component: Fetch }),
React.createElement(Route, { path: "/socket", component: Socket }),
React.createElement(Route, { path: "/form", component: Form })
)
), destination);
</script>
If used node.js then could have imported the browserHistory, but here I am using react-router library in the html page. How to overcome this issue ?
You need to import browserHistory too.
var { Router, Route, IndexRoute, IndexLink, Link, browserHistory } = ReactRouter;