Search code examples
htmlreactjsvisual-studio-codeprettier

Stop Prettier formatter from putting each HTML tag on its own line in React JSX files?


When I format an HTML file using prettier, it looks like this:

<nav>
  <ul>
    <li><a href="#" title="Home">Home</a></li>
    <li><a href="#" title="About">About</a></li>
    <li><a href="#" title="Sign Up">Sign Up</a></li>
    <li><a href="#" title="Contact">Contact</a></li>
    <li><a href="#" title="Careers">Careers</a></li>
  </ul>
</nav>

But when I put the same tags in a JSX file, it reformats it like this:

import React from "react";

const Demo = () => {
  return (
    <nav>
      <ul>
        <li>
          <a title="Home">Home</a>
        </li>
        <li>
          <a title="About">About</a>
        </li>
        <li>
          <a title="Sign Up">Sign Up</a>
        </li>
        <li>
          <a title="Contact">Contact</a>
        </li>
        <li>
          <a title="Careers">Careers</a>
        </li>
      </ul>
    </nav>
  );
};

export default Demo;

How can I stop this behavior? It happens even with a high value for prettier.printWidth


Solution

  • After more reading I've concluded this isn't possible. HTML is whitespace sensitive so it is retained, but since JSX isn't it gets autoformatted always and Prettier has no option to keep tags on the same line.