Horje
How to define state when using `history.goBack()` in React JS?

Explore the implementation of ‘history.goBack()’ in React JS, emphasizing the efficient use of states for path and route management during navigation. This article guides you through a practical project, showcasing the application of states to enhance React JS navigation.

Prerequisites:

Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command in VS Code IDE.

npx create-react-app  <folder_name>

Step 2: After creating your project folder, move to it using the following command in the VS Code terminal.

cd <folder_name>

Step 3: As we are using the React-Router package, we need to install it using the below command.

npm install [email protected]

Note: history.goBack() function is not available from react-router-dom 6.0.0. So we are installing version 5.1.2 for this example.

Project Structure:

PS-(1)

Project Structure | How to define state when using `history.goBack()` in React JS ?

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^5.1.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Approach to define state:

  • App.js Setup:
    • Main application component coded.
    • BrowserRouter used for routing.
    • Three routes defined using react-router-dom’s Route (Home, About, Contact).
  • Contact Component:
    • State object defined with relevant information.
  • Navigation:
    • Used history.push() to navigate to a new route.
    • State information sent during navigation.
    • Example: history.push('/about', { message: "Returning from Contact page" }).
  • About Component:
    • Utilized ‘useLocation()’ hook.
    • Accessed state information through location.state.
    • Displayed state data to the user.

Example: This example shows how to define state when using history.goBack() in ReactJS.

JavaScript
//App.js
import React from "react";
import {
    BrowserRouter as Router,
    Route,
    Link,
} from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";

const App = () => {
    return (
        <Router>
            <div>
                <nav>
                    <ul>
                        <li>
                            <Link to="/">Home</Link>
                        </li>
                        <li>
                            <Link to="/about">About</Link>
                        </li>
                        <li>
                            <Link to="/contact">
                                Contact
                            </Link>
                        </li>
                    </ul>
                </nav>

                <Route exact path="/" component={Home} />
                <Route path="/about" component={About} />
                <Route
                    path="/contact"
                    component={Contact}
                />
            </div>
        </Router>
    );
};

export default App;
JavaScript
//components/Home.js
import React from 'react';

const Home = () => {
    return (
        <div>
            <h1>Home Page</h1>
            <p>Welcome to GeeksforGeeks website!</p>
        </div>
    );
};

export default Home;
JavaScript
//components/About.js
import React from "react";
import { useLocation } from "react-router-dom";

const About = () => {
    const location = useLocation();
    const state = location.state;

    return (
        <div>
            <h1>About Us</h1>
            <p>
                GeeksforGeeks is a leading platform that
                provides computer science resources and
                coding challenges for programmers and
                technology enthusiasts, along with interview
                and exam preparations for upcoming
                aspirants.
            </p>
            {state && state.message && (
                <div style={
                    {
                        backgroundColor: "yellow",
                        padding: "10px"
                    }}>
                    <p>
                        Returned from: <strong>{state.message}</strong>
                    </p>
                </div>
            )}
        </div>
    );
};

export default About;
JavaScript
//components/Contact.js
import React from "react";
import { useHistory } from "react-router-dom";

const Contact = () => {
    const history = useHistory();

    const handleGoBack = () => {
        const state = {
            message: "Returning from Contact page"
        };
        history.push('/about', state);
    };

    return (
        <div>
            <h1>Contact Us</h1>
            <p>
                You can contact us at
                support@horje.org
            </p>
            <button onClick={handleGoBack}>
                Go Back
            </button>
        </div>
    );
};

export default Contact;

Step to Run Application: Run the application using the following command from the root directory of the project.

npm start

Output:




Reffered: https://www.geeksforgeeks.org


ReactJS

Related
Build a Screen Recorder in Next.js Build a Screen Recorder in Next.js
Build an Image Search App with Infinite Scroll using React JS Build an Image Search App with Infinite Scroll using React JS
React Cheat Sheet React Cheat Sheet
How to get an Element by ID in ReactJS ? How to get an Element by ID in ReactJS ?
How to set a Global Font Family in ReactJS ? How to set a Global Font Family in ReactJS ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13