What is the purpose of push() and replace() methods of history object?

The push() and replace() methods of the history object in React Router can be used to manipulate the browser's history stack and create a more seamless user experience.

The push() method adds a new entry to the history stack, while the replace() method replaces the current entry on the history stack. This allows developers to programmatically control the browser's history and change the URL displayed in the address bar without reloading the page.

For example, the push() method can be used to create a custom "link" button that takes the user to the next page of the app:

import React from 'react';
import history from 'history';
function App() {
return (
<button
id="next-button"
onClick={() => {
// Go to the next page in the app when the button is clicked
history.push('/next-page');
}}
>
Next
</button>
);
}

Or, the replace() method can be used to update the URL displayed in the address bar without reloading the page:

import React from 'react';
import history from 'history';
function App() {
return (
<button
id="update-button"
onClick={() => {
// Replace the current entry on the history stack when the button is clicked
history.replace('/updated-page');
}}
>
Update
</button>
);
}

Overall, the push() and replace() methods of the history object provided by React Router provide valuable tools for React developers who want to enhance the user experience.


October 02, 2022
25912