Property does not exist on type 'DetailedHTMLProps<ButtonHTMLAttributes

Viewed 28

I'm creating a reusable 'button' and I want to add a href to take it to another page when clicked.

ERROR:

The type '{ children: ReactNode; href: string; onMouseOver: (event: any) => void; onMouseOut: (event: any) => void; style: CSSProperties; }' cannot be assigned to type 'DetailedHTMLProps<ButtonHTMLAttributes, HTMLButtonElement>'.

Property 'href' does not exist on type 'DetailedHTMLProps<ButtonHTMLAttributes, HTMLButtonElement>'. Did you mean 'ref'?

O codigo:
import React from 'react';

type ButtonProps = {
  style: React.CSSProperties;
  children: React.ReactNode;
  href: string;
};

function MouseOver(event: any) {
  event.target.style.opacity = '90%'
}
function MouseOut(event: any) {
  event.target.style.opacity = ''
}

function Button({ style, children, href }: ButtonProps) {
  return (
      <button
      href={href}
        onMouseOver={MouseOver}
        onMouseOut={MouseOut}
        style={style}
      >
        {children}
      </button>
  )
}

export default Button;
I've already tried using this possibility:
import Link from 'next/link'

function Button({ style, children, href }: ButtonProps) {
  return (
      <Link href={href}>
        <button
          onMouseOver={MouseOver}
          onMouseOut={MouseOut}
          style={style}
        >
          {children}
        </button>
      </Link>
  )
}

This way it works, but the code requires that all buttons I'm reusing must put a href and I just want only 1 button to have the href that will take me to a page of registration.

1 Answers

As said in comments - Buttons don't have a href property; the warning you are getting is perfectly valid.

From your comment, it sounds like you want the button to be a "submit" button if there's no href, otherwise to navigate when pressed if there is a href. One thing you could do is construct the button props dynamically based on what the user passes, something like this:

type ButtonProps = {
  href?: string;
}

const handleMouseOver = (event) => event.target.style.opacity = '90%';
const handleMouseOut = (event) => event.target.style.opacity = '';

const Button = ({ 
  href,
  children, 
  ...props 
}: React.PropsWithChildren<ButtonsProps>) => {
  // Presuming you're using react-router, otherwise adjust this for
  // whatever routing package you're using.
  const navigate = useNavigate();

  // Render this as a "submit" button if no 'href' element is provided.
  // You could alternatively add a 'type' prop to `ButtonProps` to be
  // even more explicit.
  const isSubmit = !href;

  const buttonProps = {
    ...props,
    type: isSubmit ? 'submit' : 'button',
    onClick: isSubmit ? undefined : () => navigate(href),

    // Fixed props
    onMouseOver: handleMouseOver,
    onMouseOut: handleMouseOut,
  };

  return (
    <button {...buttonProps}>{children}</button>
  );
}
Related