Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you format React Component props alphabetically on save?

How does one format props and typescript definitions alphabetically on save? Ideally it is some configuration for the whole project as opposed to a VSCode plugin (though I'm open a plugin too at this point).

// the items inside ButtonProps should be sorted alphabetically
type ButtonProps = {
    name: string;
    id: string;
    onPress: () => void;
    disabled: boolean;
}

const Button = (props: ButtonProps) => {
    // this should also be sorted alphabetically
    const {name, id, onPress, disabled} = props;

    return <>My Prop</>
}

I tried react/sort-prop-types and sort-keys but I really don't know what I'm doing with eslint. It still doesn't format alphabetically on save. My eslint config is below:

// .eslintrc.json
{
  // ...
  "rules": {
    "react/sort-prop-types": [
      2,
        {
            "callbacksLast": true,
            "shorthandFirst": true,
            "ignoreCase": false,
            "noSortAlphabetically": false,
            "reservedFirst": true
        }
    ],
    "sort-keys": ["error", "asc", {"caseSensitive": true, "natural": false, "minKeys": 2}], 
  }
like image 291
wongz Avatar asked Sep 13 '25 21:09

wongz


2 Answers

You can use a VSCode extension called Sort lines. It doesn't do it on save though but all you have to do is highlight your props, press cmd + shift + p for Mac or ctrl + shift + p for Windows to open the Command Palette and select Sort lines.

like image 76
Darryl Mendonez Avatar answered Sep 15 '25 11:09

Darryl Mendonez


I tried eslint-plugin-sort-keys-fix in vscode with proper settings mentioned in https://www.npmjs.com/package/eslint-plugin-sort-keys-fix

I did not use sort-keys but just eslint-plugin-sort-keys-fix

like image 37
Amrith Raj Herle Avatar answered Sep 15 '25 12:09

Amrith Raj Herle