Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid referencing unbound methods which may cause unintentional scoping of this #3328

Open
LEECHANHYUNG opened this issue Jan 17, 2025 · 0 comments

Comments

@LEECHANHYUNG
Copy link

Bug report

Current Behavior

Currently, when passing the onOpenChange method to a component, the following ESLint warning is triggered:

Avoid referencing unbound methods which may cause unintentional scoping of `this`. If your function does not access `this`, you can annotate it with `this: void`, or consider using an arrow function instead.eslint@typescript-eslint/unbound-method

Expected behavior

The onOpenChange method should be correctly bound, and therefore, no ESLint warnings should be triggered.

Reproducible example

The current code is as follows:

import type { CollapsibleProps } from '@radix-ui/react-collapsible';

const Collapse = ({ onOpenChange, ...props }: CollapsibleProps) => {
    return (
        <Root
            onOpenChange={onOpenChange} // eslint warning triggered
            {...props}
        />
    );
};

Suggested solution

The issue can be resolved by defining onOpenChange as a function-valued property instead of a class member function:

interface CollapseProps {
  onOpenChange?: (open: boolean) => void;
}

const Collapse = ({ onOpenChange, ...props }: CollapseProps) => {
    return (
        <Root
            onOpenChange={onOpenChange} // no eslint warning
            {...props}
        />
    );
};

Additional context

This issue arises due to the difference between class member functions and function-valued properties in TypeScript's function type definitions. Class member functions can have this binding issues, whereas function-valued properties do not.

Your environment

Software Name(s) Version
Radix Package(s) @radix-ui/react-collapsible 1.1.2
React n/a 18
Browser
Assistive tech
Node n/a
npm/yarn
Operating System
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant