Languages

React - how to get the current URL?

0 points
Asked by:
mkrieger1
516

How can I get the URL from within a React component?

1 answer
0 points
Answered by:
mkrieger1
516

You can use Vanilla JS:

  • window.location.href - to get the full URL,
  • window.location.pathname.

Note:

If you are using react-router this may not work. In this case check the article: React / react-router - how to see which route we are on?

Runnable example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
   
const handleClick1 = () => {
  console.log(window.location.href);      // full URL
};

const handleClick2 = () => {
  console.log(window.location.pathname);  // path
};

const App = () => {
  return (
    <div className="App">
      <button onClick={handleClick1}>full URL</button>
      <button onClick={handleClick2}>path</button>
    </div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root );

See also

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join