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
Add a ment  | 

4 Answers 4

Reset to default 4

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>
        )
    }
}

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