Reputation: 225
I would like to print the URL in screen (yes it's written in the URL bar, but I would like to do it anyway)
What can I use ?
In the following example, what can I write instead of {iDontKnowWhatToWriteHere}
to give the curent URL ?
import React from 'react';
class Connexion extends React.Component {
render() {
return (
<h1> the URL is {iDontKnowWhatToWriteHere} </h1>
)
}
}
Thank you
Upvotes: 2
Views: 9590
Reputation: 1636
React is a normal javascript library that takes care just of the view of your application, so It allows you to access all the normal browser APIs and properties availables and one of them is location.
So if you want to access the actual url in React you should do it in the way that you would do it without React (Except when you're using some especific library for that problem like react-router), just:
If you want to get all the url (Including the domain, protocol, port)
window.location.href
Or if you just want the path after de domain
window.location.pathname
In your code
import React from 'react';
class Connexion extends React.Component {
render() {
return (
<h1> the URL is {window.location.pathname} </h1>
)
}
}
Upvotes: 4
Reputation: 731
If you are using react-router. Try:
this.props.location.pathname
Regards
Upvotes: 0
Reputation: 7474
You can get information about your url using the window.location object that is provided by vanilla JavaScript.
For reference, see https://www.w3schools.com/jsref/obj_location.asp
You could use window.location.href
to get the full url. Attached is a screenshot of the location object (I got it from Chrome web console)
Upvotes: 0
Reputation: 2614
Assuming that you use React Router
you can use
return (
<h1> the URL is {this.context.location.pathname} </h1>
)
Upvotes: 1