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:
- Import necessary dependencies:
import React from 'react';
import { Link, useLocation } from 'react-router-dom';
- 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.
- 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.