Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Call multiple functions in onClick ReactJS

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.

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

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

>Solution :

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();
}}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading