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

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

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

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

>Solution :

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
    </>
  );
}
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