Skip to content

Instantly share code, notes, and snippets.

@geekelo
Last active August 18, 2023 07:45
Show Gist options
  • Save geekelo/b4d3b41f6e90bcc792ebec31e7e1662a to your computer and use it in GitHub Desktop.
Save geekelo/b4d3b41f6e90bcc792ebec31e7e1662a to your computer and use it in GitHub Desktop.
GeekOverflow

QUESTION:

When I am on the home page I want to display a REFRESH button

When I am on the inside pages I want to display a GO BACK button instead

How can I achieve this in react

SOLUTION

To achieve the desired behavior of displaying a refresh button on the home page and a back button on inside pages in a React application, you can use conditional rendering based on the current route. You can use the useLocation hook from react-router-dom to get the current location, and then determine whether to display the refresh or back button.

Here's how you can achieve this:

  1. Import necessary dependencies:
import React from 'react';
import { Link, useLocation } from 'react-router-dom';
  1. Inside your component, use the useLocation hook to get the current location and conditionally render the buttons:
function NavigationButtons() {
  const location = useLocation();

  // Determine if we're on the home page (root path)
  const isHomePage = location.pathname === '/';

  return (
    <div>
      {isHomePage ? (
        <button onClick={() => window.location.reload()}>Refresh</button>
      ) : (
        <Link to="/">Back</Link>
      )}
    </div>
  );
}

In this example, we check if the current pathname is the root path ('/') to determine if we're on the home page. If we're on the home page, we render a refresh button that triggers a page reload when clicked. Otherwise, we render a back button that navigates back to the home page.

  1. Render the NavigationButtons component within your layout or navigation area:
function App() {
  return (
    <div>
      {/* Your other components */}
      <NavigationButtons />
    </div>
  );
}

Make sure you have set up your react-router-dom routes correctly, and the NavigationButtons component should be placed within a part of your layout where you want the buttons to appear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment