EN
React - how to get the current URL?
1
answers
0
points
How can I get the URL from within a React component?
1 answer
0
points
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