How to read the current URL in the react application - javascript

I would like read and print the current URL in the react application. Right now i am using "window.location.pathname" to read the URL but would like to know if there is a better way or some react way to read the URL

window.location.href
returns the href (URL) of the current page
window.location.hostname
returns the domain name of the web host
window.location.pathname
returns the path and filename of the current page
window.location.protocol
returns the web protocol used (http: or https:)

if you are using React Router and your component is rendered by a Route like below for example:
<Route exact path='/' component={HomeComponent}/>
that component will automatically receive three objects from Route named history , location and match respectively. by that you can find what you asked under location.pathname. more info here
if you still using react router and your component is not been rendered with Route , you need to use withRouter , which is a HOC and will give you history , location and match as props to your component. more info here
if you are not using react router you gonna need to use window.location.pathname or window.location.href or only location.pathname

If you are using react router:
const currentRoute= this.props.location.pathname
else you can get this like:
const currentRoute= window.location.pathname
href will give you complete url.

We can get it from this.props using withRouter component from react-router-dom package in the following way by adding in the class
import React from 'react';
import { connect } from 'react-redux';
import { Switch, Route, withRouter } from 'react-router-dom';
class Application extends React.PureComponent {
render() {
console.log(this.props)
this.props.location.pathname // we will get the pathname
return (
<div className='application'>
{Hi}
</div>
);
}
}
export default connect(mapStateToProps, actions)(withRouter(Application));
output:

You can use the useParams hook to access values in your URL. When creating your routes in App.jsx you will specify the name of the input variable like this:
<Route
path="/search/:searchType/:module/:category/:search/:source"
exact={true}
component={yourComponent}
/>
Then you can use the useParams hook inside your component to access the variable values.
const {searchType, module, category, search, source} = useParams();

if you using react js then use useLocation and useHistory hooks
import { useHistory ,useLocation } from 'react-router-dom';
const location = useLocation()
console.log(location.pathname)
const history = useHistory()
console.log(history.location.pathname)

Related

What is the alternative for match in react router dom v6?

Recently I started upgrading from react-router-dom v5 to v6 and I have something in my Route which I don't know what it is and what is the alternative in react-router-dom v6. The keyword match inside <LayoutReport match={props} /> is giving me warning:
(property) match: any
Type '{ match: any; }' is not assignable to type 'IntrinsicAttributes'.
Property 'match' does not exist on type 'IntrinsicAttributes'.ts(2322)
This is my Route
<Route
path="reports/*"
element={props => (
<FilterBarProvider>
<LayoutReport match={props} />
</FilterBarProvider>)}
/>
It seems you are asking two questions, one about the Typescript error/warning, and the other is an implied "how to access route props in RRDv6" via the title. Answering the second rather resolves the first. In react-router-dom#6 there are no longer any route props. In fact, the element prop takes only a React.ReactNode, a.k.a. JSX, not any callback function that may or may not return JSX.
The route should look something like:
<Route
path="reports/*"
element={(
<FilterBarProvider>
<LayoutReport />
</FilterBarProvider>
)}
/>
This will remove the Typescript error/warning about the match prop that was passed.
But now how to access the old RRDv5 match object? This is easy, use React hooks to access what was previously provided on the match object. For example, if you are trying to access route path params, use the useParams hook to access the params object, i.e. what used to be match.params.
import { useParams } from 'react-router-dom';
const LayoutReport = () => { // <-- remove undefined `match` prop
const params = useParams(); // <-- access params via hook
...
};
There are other hooks to access other route information, so it depends on what you need to access which hook you use.
history object was replaced by a navigate function via the useNavigate hook
location object via the useLocation hook
match object was eliminated, you can access the params via the useParams hook.
Example:
import { useLocation, useNavigate, useParams } from 'react-router-dom';
const LayoutReport = () => {
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
...
};
you can use the useParams hook. https://reactrouter.com/en/v6.3.0/api#useparams

Leading Hashtag In A React Router Path

I'm refactoring an API front-end from jQuery to React and in order to keep the site backward-compatible, I have to keep the current URL formatting to match: www.site.com/#parameter, which has a leading hashtag in the pathname. The problem comes when trying to route the pathname to match this format, React Router doesn't recognize the route or render the corresponding components. When trying to console.log the useParams object, it returns undefined.
TLDR; How can I access a URL parameter that starts with a ‘#’?
import {Switch, Route} from "react-router-dom"
import Home from "./Home"
function Routes() {
return (
<div>
<Switch>
<Route exact path={`/#:parameter`}><Home/></Route>
</Switch>
</div>
)
}
export default Routes;
Have your heard about HashRouter from React Router? It's main functionality is to replace BrowserRouter to handle legacy systems and the overall route looks like this:
www.your-great-website.com/#route-name
That might be what you're looking for or it will give you a starting point hopefully
Here's the official docs from the React Router team - HashRouter

How to properly use useHistory () from react-router-dom?

How to use useHistory() correctly? I can't make the transition from one react component to another.
According to the instructions from the React documentation and also here on Stack Overflow, I cannot make the transition from App.js to MyComponent.js.
For example - I am trying
/* **App.js ** */
/* Import modules */
import React from 'react';
import { useHistory } from 'react-router-dom'; // version 5.2.0
function App()
{
let history = useHistory ();
const handleClick = () => {
history.push ('./pages/MyComponent');
}
return (
<div className="App">
<button onClick={handleClick}>Next page ==></button>
</div>
);
}
I also tested this example, but the output throws the following error when the button is pressed:
TypeError: Cannot read property 'push' of undefined
Does something seem to be leaking to me or is there a mistake on Babel's side?
Project react structure:
+ Root/
+ src/
- App.js
- index.js
+ pages/
- MyComponent.js
This has changed in v6, useHistory is now useNavigate and we can use it as follows:
instead of:
const history = useHistory()
history.push('/')
we now use:
const navigate = useNavigate()
navigate('/')
You can't just use the useHistory hook to redirect to another page.
You need to properly set up your application in order to use React Router. Look at their examples starting from this https://reactrouter.com/web/example/basic
You need to wrap your entire application with <BrowserRouter /> which will give the history object you are looking for through the hook.
By the way, you don't give a relative file path to history.push as an argument, you must give a valid route that you typically setup using <Route /> component
Using history.replace('/<route-name>') also works.
you need to use it with react-router-dom. set your router config and then push it to that path. you can get more information by looking at documentation.
https://reactrouter.com/web/example/route-config
do not forget to set your switch components and your exact for root path.
Using React 17.0>, this works for me:
import { useHistory } from "react-router-dom";
const history = useHistory();
history.push("/home");
I've reached too much to find this correctly use of the useHistory function.
Try and answer this post for feedback.
When you are applying history.push, is that your path name? history.push('/pathname') is the process I guess.
You can see here: https://reactrouter.com/web/api/Hooks

React.js how to access a parameter in a Router Link URL from a function Component?

I had access to params from a router URL by using the following:
${this.props.match.params.id}.
is there a way to access the same param from a functional component as opposed to a class component?
You can use the withRouter hoc provided by react-router :
You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
import { withRouter } from 'react-router';
const Component = props => ...
// now you can access props.history|match|location
const ComponentWithRouteProps = withRouter(Component);

React Router Dom (4) Programmatically Navigate

I am working on a React app that is 'remote controlled' and am trying to connect the app's tab navigation via Pusher. I am using react-router-dom and have set up my connection to Pusher and the channels it listens to in the componentDidMount. I need to have the app change URL navigation each time a message is returned but cannot figure out what the correct way to 'push' it is. I have google many threads about programmatically navigating react-router-dom and have tried this.history.push(), this.props.history.push() and it's always throwing an error that history is undefined. The listeners reside in the same Component as the routing itself.
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import axios from 'axios';
import Pusher from 'pusher-js';
import Component1 from './Component1';
import Component2 from './Component2';
export default class AppRouter extends Component{
componentDidMount() {
const pusher = new Pusher('8675309', { cluster: 'us2', encrypted: true });
const nav_channel = pusher.subscribe('nav');
nav_channel.bind('message', data => { this.props.history.push(data.message) });
}
...
render(){
return(
<Router>
<Switch>
<Route path='/path1' render={() => <Component1 navigate={this.handleNavChange} />} />
<Route path="/path2" render={() => <Component2 navigate={this.handleNavChange} />} />
</Switch>
</Router>
)
}
}
I need the app to change the URL or the routing each time the message is received from another connected app but I cannot figure out how to make react-router-dom (v4) do it within the same component as the Router itself. Any information or pointing me to a resource would be highly appreciated.
You need to use the withRouter decorator from React-Router to get access to match, location, and history.
import { withRouter } from 'react-router'
Wrap your component when exporting
export default withRouter(yourComponent)
Then you will have access to history from props.
https://reacttraining.com/react-router/core/api/withRouter
To add on to andrewgi's answer:
After using withRouter() on your component, OR a parent component,
try the following code in your component:
static contextTypes = {
router: PropTypes.object,
location: PropTypes.object
}
These should be defined, you can try console.log(this.context.router, this.context.location)
Then, to navigate programmatically, call
this.context.router.history.push('/someRoute');
Note: the context API is not stable. See Programmatically navigate using react router and https://reactjs.org/docs/context.html#why-not-to-use-context.

Categories

Resources