Search code examples
javascripthtmlreactjsyarnpkgvite

react onclick function loading as "function noop() {}"


i have no idea why this is happening, but for some reason in firefox my react project using tsx running under vite. and i'm trying to run this function on click/tap which dynamically changes the header and what it does when the logo is clicked. the code in question is:

function Logo() {
  return (
    <a
      href={window.innerWidth > 600 ? "/home" : undefined}
      onClick={() => {
        if (window.innerWidth <= 600) {
          // run your function here
          if (document.getElementById("header")!.style.height === "3rem") {
            document.getElementById("header")!.style.height = "100vh";
            // document.getElementById('header')!.style.top = '3rem';
          } else if (
            document.getElementById("header")!.style.height === "100vh"
          ) {
            document.getElementById("header")!.style.height = "3rem";
          } else {
            // Do something else if necessary
          }
        }
      }}
    >
      <div>
        <img
          src="./src/assets/mediaKits/reineYurkowskiAssets/initialsThicc.svg"
          alt="Reine Yurkowski's signature"
          style={{ transform: "scaleX(1.5) skew(10deg, 10deg)" }}
        />
      </div>
    </a>
  );
}

but for some reason when i try running it from a local port using yarn dev it loads as: "function noop() {}".

it was working for a bit before somehow just giving up and not working further.

i attempted doing multiple things like making this a function and just calling it, coding it in a tag, using gpt, and a bunch of others, but none seem to work and i can't seem to understand specifically why this is happening.

any help would be greatly appreciated thank you.


Solution

  • A React elements onClick property is not the same as a HTML elements 'onclick' property.

    React handles events "behind the scenes", at the root element, and attaches a noop() handler to the actual HTML elements.

    But these are implementation details you are not supposed to care about.

    The main problem is very likely that you are manipulating the DOM manually, which you should never do in React.

    Instead, you should e.g. set some state in the onClick handler, and build the header component (with JSX, not with DOM methods) according to the state.

    E.g.

    const [ height, setHeight ] = useState('3rem');
    
    // ...
    
    <a href="..." onClick={ function(){
        if( height === "3rem" ){
            setHeight("100vh");
        }
    }} >
    
    // ...
    
    <MyHeader style={{ height: height }} />