When you start a react native project or any other projects witch involves javascript, it’s important to setup some basic rules for your code, so let’s with Eslint and Prettier.
If you don’t know what is Eslint check the documentation to make an idea, and for Prettier you can find more details here.
A general idea is to set some rules for your JavaScript code with Eslint and then run Prettier for code formatting, let’s add this to a react native app.
First step is to install
and eslint
with yarn: eslint-config-airbnb
and then yarn add eslint -D
with some dependencies eslint-config-airbnb
.add eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react -D
Second step for this setup is to install Prettier:
. Create a yarn add prettier eslint-config-prettier eslint-plugin-prettier -D
file in the root of the project and add the fallowing rules: .eslintrc
{ "extends": [ "airbnb", "prettier", "prettier/react" ], "rules": { "prettier/prettier": [ "error", { "trailingComma": "es5", "singleQuote": true, "printWidth": 100 } ], "react/jsx-filename-extension": [ 1, { "extensions": [ ".js", ".jsx" ] } ], "react/prop-types": [ "error", { "ignore": [ "navigation" ] } ], "react-native/no-unused-styles": 2, "react-native/split-platform-components": 2, "react-native/no-inline-styles": 2, "react-native/no-color-literals": 2, "react-native/no-raw-text": 2, }, "plugins": [ "react", "react-native", "prettier" ],
Now that you have some basic rules defined you can add other settings in your
file to run your eslint and prettier. What i did in my react native project was to add an extra plugin to check my JavaScript code when i want to commit something. package.json
Add new modules to prevent committing bad code to your repository:
and then create a small configuration in yarn add husky lint-staged pretty-quick -D
file:package.json
"scripts": { "prettier": "prettier 'app/**/*.js'", "pre-commit": "lint-staged" }, "husky": { "hooks": { "pre-commit": "lint-staged", "flow": "yarn run flow" } }, "lint-staged": { "*.{js,jsx}": [ "yarn run prettier", "eslint --fix", "git add" ] }
As you can see in the above JSON we have a setup for Eslint and Prettier and we are ready to commit our progress to a repository. If you want to use Redux check this article about Setup redux to a react native app .