Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript Data Type onClick null doesnt work

I try to learn from some Javascript tutorial but I want make this app using typescript.

import PropTypes from 'prop-types';
import './button.scss'

const Button = (props: any | null | undefined) => {
  return (
    <button
      className={`btn ${props.className}`}
      onClick={props.onClick ? () => props.onClick() : null}
    >
      {props.children}
    </button>
  )
}

export const OutlineButton = (props:any | null | undefined) => {
  return (
    <Button
      className={`btn-outline ${props.className}`}
      onClick={props.onClick ? () => props.onClick() : null}
    >
      {props.children}
    </Button>
  )
}

Button.prototype = {
  onclick: PropTypes.func
}

export default Button

I got error on this code onClick={props.onClick ? () => props.onClick() : null}

it say

Type '(() => any) | null' is not assignable to type 'MouseEventHandler<HTMLButtonElement> | undefined'.
  Type 'null' is not assignable to type 'MouseEventHandler<HTMLButtonElement> | undefined'.ts(2322)
index.d.ts(1489, 9): The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>'
(property) React.DOMAttributes<HTMLButtonElement>.onClick?: React.MouseEventHandler<HTMLButtonElement> | undefined

Can you help me to fix this data type ?

like image 487
Mind Mon Avatar asked Aug 26 '26 11:08

Mind Mon


1 Answers

You can conditionally pass an onClick function to the Button component based on whether the props object contains the onClick property. Here's an example of how you can achieve this:

<div>
  {props.onClick ? (
    <Button onClick={props.onClick}>{props.children}</Button>
  ) : (
    <Button>{props.children}</Button>
  )}
</div>

I tried to refactor the code using TypeScript.

import React, { FC } from 'react';
import PropTypes from 'prop-types';
import './button.scss';

type ButtonProps = {
  className?: string;
  onClick?: () => void;
};

const Button: FC<ButtonProps> = ({ className, onClick, children }) => {
  const handleClick = () => {
    if (onClick) {
      onClick();
    }
  };

  return (
    <button className={`btn ${className}`} onClick={handleClick}>
      {children}
    </button>
  );
};

Button.propTypes = {
  onClick: PropTypes.func
};

export const OutlineButton: FC<ButtonProps> = ({ className, onClick, children }) => {
  const handleClick = () => {
    if (onClick) {
      onClick();
    }
  };

  return (
    <Button className={`btn-outline ${className}`} onClick={handleClick}>
      {children}
    </Button>
  );
};

export default Button;
like image 73
Jason Jin Avatar answered Aug 28 '26 02:08

Jason Jin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!