Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to router directly by typing it's address on the address bar in react-router

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.]

like image 915
fue Avatar asked Mar 24 '17 14:03

fue


People also ask

How do I route a router using react?

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.

How do I access location react router?

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 .

Which part of URL is used by react router to match routes?

path - (string) The path pattern used to match. Useful for building nested <Route> s. url - (string) The matched portion of the URL.

How do you route to external URL in react?

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.


1 Answers

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

like image 90
Associate Avatar answered Sep 21 '22 13:09

Associate