Categories
React Answers

How to fix the newlines character ignored by JSX tables issue with React?

Spread the love

Sometimes, we want to fix the newlines character ignored by JSX tables issue with React.

In this article, we’ll look at how to fix the newlines character ignored by JSX tables issue with React.

How to fix the newlines character ignored by JSX tables issue with React?

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.

For instance, we write:

import React from "react";

export default function App() {
  return (
    <>
      <style>
        {`.pre-wrap {
          white-space: pre-wrap
        }`}
      </style>
      <table>
        <tbody>
          <tr>
            <td className="pre-wrap">
              {
                "Line 1\nLine 2\nLine 3\nThis is a cell with white-space: pre-wrap"
              }
            </td>
          </tr>
        </tbody>
      </table>
    </>
  );
}

We have a string that have some new line characters between a few substrings.

To make them display in separate lines, we add the pre-wrap class which sets the white-space CSS property to pre-wrap.

And we set the className of the td to pre-wrap to apply the styles.

Now we should see that each line in the string are displayed on separate lines.

Conclusion

To fix the newlines character ignored by JSX tables issue with React, we can set the white-space CSS property to pre in the cell.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *