skip to Main Content

I imported a component from another file. I want to change the state of showModal to true with one click. I wrote a console log in the function to see if the function is running. However, nothing happens in the DevTools. No error message and no log. Is my attempt possible?

function Nav() {
  const [showModal, setShowModal] = useState(false);
  const openModal = () => {
    setShowModal((showModal) => !showModal);
    console.log("klicked");
  };
  return (
    <header>
      <div>
        <div>
          <AddTaskBtn onClick={openModal} />
        </div>
      </div>
      <Modal showModal={showModal} setShowModal={setShowModal} />
    </header>
  );
}
function Modal({ showModal, setShowModal }) {
  return (
    <>
      {showModal ? (
          <div className="modalwrapper">
            <div className="modalheader">
              <button onClick={() => setShowModal((prev) => !prev)}>
                Modal close
              </button>
            </div>
          </div>
      ) : null}
    </>
  );
}
export default Modal;

I tried a direct function call. But also no error message and no log.

3

Answers


  1. Can you provide more details about
    Button Component:
    Double-check that the "AddTaskBtn" component (<AddTaskBtn />) is implemented correctly and has the onClick handler attached. Verify that it correctly triggers the openModal function when clicked.

    Login or Signup to reply.
  2. At first change name of param in openModal

    const openModal = () => {
        setShowModal(prevShowModal => !prevShowModal);
        console.log("clicked");
      };
    

    Also it’ll be better to set value to false in modal:

    <button onClick={() => setShowModal(false)}>
      Modal close
    </button>
    

    Second issue. Maybe button is disabled or overplayed by any other item. You need to check this too.

    This should help

    Login or Signup to reply.
  3. Well you need to attach onClick to a native element, your AddTaskBtn component needs to accept onClick as a prop and use it inside of it, for eg:

    const AddTaskBtn = ({ onClick }) => {
        return <button onClick={onClick}>click me</button>
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search