admin管理员组文章数量:1394781
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
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
Share Improve this question edited Aug 23, 2017 at 18:15 Maxim Kuzmin 2,61421 silver badges24 bronze badges asked Aug 22, 2017 at 19:10 droledenomdroledenom 2252 gold badges6 silver badges18 bronze badges 1- 1 window.location.href – Prakash Sharma Commented Aug 22, 2017 at 19:13
4 Answers
Reset to default 4React 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>
)
}
}
Assuming that you use React Router
you can use
return (
<h1> the URL is {this.context.location.pathname} </h1>
)
You can get information about your url using the window.location object that is provided by vanilla JavaScript.
For reference, see https://www.w3schools./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)
If you are using react-router. Try:
this.props.location.pathname
Regards
本文标签: javascriptPrinting the current URL in ReactJSStack Overflow
版权声明:本文标题:javascript - Printing the current URL in ReactJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744101978a2590904.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论