Prettier is a code formatting tool that automatically applies desired code styling for you in your project. Code formatting is not something that we should be worried about as engineers. Our attention is quite valuable and should be going to the difficult tasks. Prettier handles some of the boring aspects of coding and maintains consistency.

Installation

To install Prettier in your project run

npm install --save-dev --save-exact prettier

in the root directory of your React project.

The next step is to create the config file.

echo {}> .prettierrc.json

You can also create the .prettierignore file which works exactly as .gitignore, but in the aspect of code formatting.

Usage

Let’s shift our attention to the App.js in which I have written the classic example in which I’m creating a piece of state and then render it to the page.

import React, { useState } from 'react'
import './App.css'

function App() {
 const [user, setUser] = useState({name:'Tommy',surname:'Smith',age:12});
return (
  <div style={{ margin: '50px' }}>
  <h1>Current User:</h1>
  <h2>Name: {user.name}</h2>
  <h2>Surname: {user.surname}</h2>
  <h2>Age: {user.age}</h2>
  </div>
  );
}

export default App;

If you paid a bit more attention then you probably noticed that the code is formatted in a really odd way. I wasn’t bothered very much with using proper indentation and making it very readable. Normally I would have had to go over the App component manually and fix all of the issues, but I can use Prettier to handle all of this for me.

I’m simply going to run

npx prettier --write .

in the root directory. This command will go over all of the files in my project and format them for me. Let’s run it.

The above log output appeared in my console. It lists all of the files that were formatted by Prettier and the time that it took.

Let’s take another look at App.js.

import React, { useState } from "react";
import "./App.css";

function App() {
  const [user, setUser] = useState({
    name: "Tommy",
    surname: "Smith",
    age: 12,
  });
  return (
    <div style={{ margin: "50px" }}>
      <h1>Current User:</h1>
      <h2>Name: {user.name}</h2>
      <h2>Surname: {user.surname}</h2>
      <h2>Age: {user.age}</h2>
    </div>
  );
}

export default App;

Doesn’t it look much better?

Prettier is highly customisable. There are a lot more ways in which you can configure it to fit your needs. Please make sure to take a look at the official docs to see how it can help you.

👋 Hey, I'm Dawid Budaszewski
Hello! I'm Dawid. I'm a full-stack developer with a couple of years of experience under my belt. I spent most of my career working with React. Now it's time to pass the knowledge onto somebody else!

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.