-2

The issue lies within the <Button> component, specifically in its onClick event handler, which needs to perform two tasks:

  1. Navigate back to the previously visited route using the useNavigate hook.

  2. Change the name of the button from "GoBack" to "Home" by passing appropriate props.

CodeSandBox

In codeSandBox go to the src/Home.js file

import React from 'react';
import { Button } from '@mui/material';
import { useLocation, useNavigate } from 'react-router-dom';

const Home = (props) => {
    const history = useNavigate();
    return (<div style={{ height: '100vh' }} className={`text-${props.mode} bg-${props.dmode}`}><h1 >{props.Name}</h1>
        <Button variant="contained" color="success" onClick={() => { () => (history(-1)); props.toggleHomeBTN }}>{props.home}</Button>
    </div>)
}

export default Home;

ERROR

enter image description here

Already referred StackOverFlow Questions

How can I implement a functionality where, upon clicking a button on the root route ("/") page, the user is redirected to the previously visited page, and the button's text changes from "Go Back" to "Home" using props?

CodeSandBox

https://codesandbox.io/s/angry-cartwright-3stjj3

Drew Reese
  • 165,259
  • 14
  • 153
  • 181

1 Answers1

0

You need to invoke the props.toggleHomeBTN function like this:

onClick={() => {
  history(-1);
  props.toggleHomeBTN?.();
}}

The ?. operator will handle the invoked function being undefined or null. You can read more about it here.

It can be potentially omitted and in that case the code would look like this:

onClick={() => {
  history(-1);
  props.toggleHomeBTN();
}}
Tony Troeff
  • 338
  • 4
  • 19