There is two "main" way to use react-router (V4); The first way is using hash router which you can access directly to an address by typing it on browser's address bar but you must add a # to URL, another way is using BrowserRouter which has a pretty and user-friendly URL structure but you can't directly type the address to render the route.
How I can config HashRouter to work without # or config BrowserRouter to work with directly URL typing, too? Is it possible with .htaccess? How?
const React = require('react');
const ReactDOM = require('react-dom');
import { HashRouter as Router, Route, Link} from 'react-router-dom';
const routes = (
<Router forceRefresh={false}>
<div>
<Route exact path="/" component={Firstpage}/>
<Route exact path="/projects" component={Projectslist}/>
</div>
</Router>
);
ReactDOM.render(routes, document.getElementById('app'));
[In this type it works with a # mark. e.g.: localhost:2000/#/projects ]
Another type:
const React = require('react');
const ReactDOM = require('react-dom');
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';
const routes = (
<Router forceRefresh={true}>
<div>
<Route exact path="/" component={Firstpage}/>
<Route exact path="/projects" component={Projectslist}/>
</div>
</Router>
);
ReactDOM.render(routes, document.getElementById('app'));
[And in this type it works well without a # mark, but it's not possible to load it directly on the browser's address bar.]
Using React Router: To use React Router, let us first create few components in the react application. In your project directory, create a folder named component inside the src folder and now add 3 files named home. js, about. js and contact.
Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .
path - (string) The path pattern used to match. Useful for building nested <Route> s. url - (string) The matched portion of the URL.
Navigating to an external page in React To navigate to another page, set the window. location. href property with the URL: // 👇️ directly change the active URL to navigate window.
If you are using webpack-dev-server, you need to set historyApiFallback: true
in your config file.
https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With