eslint-plugin-react icon indicating copy to clipboard operation
eslint-plugin-react copied to clipboard

Add Rule option "disallowedFor" for component prop

Open jacketwpbb opened this issue 1 year ago • 1 comments

Suppose we have a component that accept a prop named string.

function Comp(props) {
    return <div>{props.string}</div>;
}

function App() {
    return <Comp string="213"  />;
}

As needs change, we need to replace string prop by another named number.


function Comp(props) {
    return <div>{props.number || props.string}</div>;
}
Comp.propTypes = {
    number: PropTypes.number,
    /**
     * @deprecated use number instead
     */
    string: PropTypes.string
};
Comp.defaultProps = {
    string: '123',
    number: 123
};

The string prop will works in a period of time, but it's better to replace it with number prop. This rule option can be use to avoid using deprecated prop for Comp.

{
"react/forbid-component-props": [
    "error", { "forbid": [{"propName": "string", "disallowedList": ["Comp"]}] }
  ]
}

image

jacketwpbb avatar Sep 08 '22 04:09 jacketwpbb

Since it's marked as deprecated with jsdoc, there's eslint-plugin-deprecated - and if you're using TS, it will catch it too.

Why can't you just remove it and make a major bump?

ljharb avatar Sep 08 '22 17:09 ljharb

Hello, I would also like this: my use case is for discouraging the usage of props in components that I don't control, and thus can't annotate or alter the component myself.

Specifically, I want to disallow the required parameter on Ant Design's Form.Item to avoid confusion with a require parameter I'm adding in HOCs that we create. And generally I dislike the required parameter in Ant Design 4.x even without the conflicting HOC parameter, I find it inherently confusing - it only applies styling, and doesn't actually enforce validation, which is very surprising to me.

I could wrap Form.Item in an HOC and use that instead, but that doesn't prevent others from using the original component, so it doesn't really get me very far. I also don't want to create an HOC and than ban the original altogether, because that would be a much larger change for not a lot of benefit.

I want to be able to mark props as disallowed in libraries that I don't control, and allowedFor on this rule seems like the way to accomplish that. I'm not often one to question library's decisions, sometimes there are exceptions and I want to just avoid using a feature because it is too confusing or troublesome, and this is one of those cases.

cincodenada avatar Mar 28 '23 20:03 cincodenada

@cincodenada you can prevent them from using the original component using no-restricted-imports and/or no-restricted-properties, fwiw.

That said, thanks, that is a reasonable use case.

ljharb avatar Apr 14 '23 19:04 ljharb