javascriptevent-listenerremix.run

onClick event listeners are not working in Remix


In my Remix app, I'm trying to conditionally display a UI widget, based on the value of a state variable. Here is my code.

import { useState } from "react";
import type { LinksFunction } from "remix";
import stylesUrl from "../styles/index.css";

export const links: LinksFunction = () => {
  return [
    {
      rel: "stylesheet",
      href: stylesUrl
    }
  ];
};

export default function Index() {
  const [isMenuOpen,setMenuOpen] = useState(false)

  function toggleNav(){
    window.alert("hh") // no alert is shown
    console.log("hi") // no console statement is printed
    setMenuOpen(!isMenuOpen)
  }

  return (
    <div className="landing">
     <button onClick={toggleNav}>test</button>
    </div>
  );
}

However, toggleNav function doesn't seem to be triggered on button click. I couldn't see any alert or output in the console.

I couldn't understand why it's not working. It would be great, if someone can point me out what I'm doing wrong here. TIA.


Solution

  • Ensure that you are rendering the Scripts component from Remix in the root route, without it you app will not load any JS client side.

    See https://remix.run/docs/en/v1/api/remix#meta-links-scripts