2

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

1
  • 1
    window.location.href Commented Aug 22, 2017 at 19:13

4 Answers 4

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>
        )
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming that you use React Router you can use

return (
    <h1> the URL is {this.context.location.pathname} </h1>
)

Comments

0

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)

enter image description here

Comments

0

If you are using react-router. Try:

this.props.location.pathname

Regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.