Skip to content
Advertisement

Event handler not displaying component

on clicking <button>, a click handler is invoked, in which a react component <ConfirmationDialog> is returned. But <ConfirmationDialog> is not getting invoked and displaying. why?

// App.js

import ConfirmationDialog from "./ConfirmationDialog";

export default function App() {
  const handleClick = () => {
    console.log("handle click");
    return <ConfirmationDialog />; // called from click handler
  };
  return <button onClick={handleClick}>click</button>;
}

// ConfirmationDialog.js

import * as React from "react";

export default function ConfirmationDialog() { // child component
  console.log("confirmation dialog");
  return <p>Confirmation dialog component</p>;
}

Why is click handler handleClick not rendering <ConfirmationDialog> ?

CodeSandbox Demo

Advertisement

Answer

See the updated codesandbox

Because you are returning a component from a function that is called within an event handler. You need to use state to actively hide or show components in the way you want.

In this case we have a state that is initally set to false, this state determines whether to show the confirmation box or not, in the handle click function, we set the state to true which allows the confirmation box to become visible. If the state were to be set to false once again, then the confirmation box would become invisible.

import ConfirmationDialog from "./ConfirmationDialog";
import { useState } from "react";

export default function App() {
  const [confirm, setConfirm] = useState(false); //state that determines whether to show confirm box or not
  const handleClick = () => {
    console.log("handle click");
    setConfirm(true); // decide to show the confirmation box
  };
  return (
    <>
      <button onClick={handleClick}>click</button>
      {confirm && <ConfirmationDialog />} // condition for showing the confirmation dialog
    </>
  );
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement