Search code examples
reactjsvisual-studio-codejsxprettier

Why is VS Code's Prettier extension replacing spaces with {" "} in JSX?


Every time I save (format on save) a file, Prettier decides to add me this (talking about coding in JS with React): {" "} or {' '}

Why does this happen? Is it a good thing? If not, how can I make it stop happening?


Solution

  • Well, it's one of the things that can't be prettier and we probably have to get used to it.

    If you check the React documentation, you can see that with JSX trailing and leading whitespaces on a line are removed:

    JSX removes whitespace at the beginning and ending of a line. It also removes blank lines. New lines adjacent to tags are removed; new lines that occur in the middle of string literals are condensed into a single space.

    If you need a space to show up between text and a following element on the next line, you have to add {" "}. You just can't avoid it. The ugly spaces are actually semantically important to JSX.

    Original:

    <section>
      <ul>
        <li>There is <strong>no problem</strong> with long texts without inline elements starting on new lines. Lorem ipsum dolor, sit amet consectetur adipisicing elit. Laboriosam vero enim eos iste! Odio deserunt id quam.</li>
        <li>But if there are inline HTML elements on new lines... Soluta culpa dolor <a href="#officia">officia omnis</a> fugiat ipsa! Corporis, ex amet hic incidunt explicabo? Alias <strong>libero temporibus, corporis recusandae</strong> <em>voluptatibus</em> eligendi.</li>
      </ul>
    </section>
    

    Formatted:

    <section>
      <ul>
        <li>
          There is <strong>no problem</strong> with long texts without inline
          elements starting on new lines. Lorem ipsum dolor, sit amet consectetur
          adipisicing elit. Laboriosam vero enim eos iste! Odio deserunt id quam.
        </li>
        <li>
          But if there are inline HTML elements on new lines... Soluta culpa dolor{" "}
          <a href="#officia">officia omnis</a> fugiat ipsa! Corporis, ex amet hic
          incidunt explicabo? Alias{" "}
          <strong>libero temporibus, corporis recusandae</strong>{" "}
          <em>voluptatibus</em> eligendi.
        </li>
      </ul>
    </section>;