React Js Change Url Dynamically
React Js Change Url Dynamically : In React.js, you can change the URL dynamically by utilizing the window.location.href
property. This property represents the complete URL of the current page. By assigning a new value to it, you can navigate to a different URL programmatically. For example, window.location.href = '/new-url'
will redirect the user to the '/new-url' page. This approach is commonly used in React.js applications to implement client-side navigation or to perform redirects based on certain conditions or user interactions.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I dynamically change the URL in React.js?
In this React.js code snippet, the changeURL
function is defined to dynamically change the URL. It uses the window.location.href
property to set the new URL. The App
component renders a container div with a heading and a button. When the button is clicked, it invokes the changeURL
function with a new URL parameter ('fa/react-js-get-random-item-from-array'), effectively changing the URL dynamically.
React Js Change Url Dynamically Example
xxxxxxxxxx
<html>
<head>
<meta charset="UTF-8" />
<script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/babel">
const { useState } = React;
function App() {
const changeURL = (newURL) => {
window.location.href = newURL;
};
return (
<div className='container'>
<h3>React Js Change URL Dynamically</h3>
<button onClick={() => changeURL('fa/react-js-get-random-item-from-array')}>Change URL</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
</body>
</html>