React Hooks onClick event: call child function before calling parent function

Viewed 77

In my code below, how to call executeBeforeToggle function before executing parent's function togglePage?

import * as React from "react";
import { useState } from "react";
import { render } from "react-dom";

const Page1 = (props) => {  

  //how to call this function before toggling?
  const executeBeforeToggle = () => {
    alert('HOORAY')
  }

  return (
      <div>
        <h1>I am Page 1</h1>
        <button onClick={() => props.togglePage()}>Toggle</button>
      </div>      
    )
};

const Page2 = (props) => {
  return (
    <div>
      <h1>I am Page 2</h1>
      <button onClick={() => props.togglePage()}>Toggle</button>
    </div>      
  )
}

const App = () => {
  const [page, setPage] = useState(false)

  const togglePage = () => {    
    setPage(!page)
  }


  if(page === false) return <Page1 togglePage={togglePage} />
  else return <Page2 togglePage={togglePage}  />
}



render(<App />, document.getElementById("root"));
1 Answers

Not sure if I understood your question correctly, but actually that is simple:

const Page1 = (props) => {  

  const executeBeforeToggle = () => {
    alert('HOORAY')
  }

  const handleClick = () => { // click handler which exec both funcs
    executeBeforeToggle();
    props.togglePage();
  }

  return (
      <div>
        <h1>I am Page 1</h1>
        <button onClick={handleClick}>Toggle</button>
      </div>      
    )
};

So the main idea is that your click handler should be a function which executes both executeBefore and togglePage functions in the order you need. You may write that right inside the buttons onClick, or (as above) create separate function and pass it into the onClick what makes code a bit more readable.

Related