Search code examples
reactjswhitespace

Why react doesn't render whitespaces


I have the following example:

<h1>{errors.email?.message || ' '}</h1>

Which means: If there is an error message, display it, else display a normal space.
The problem I faced is that react shows the error if it's available, else it doesn't show anything, in other words, the space string is always ignored and will be never displayed.

Why is this happening and how can I show a string that contains only a whitespace


Solution

  • You'll be able to display only whitespace by using the white-space property:

    function App() {
        return <h1 style={{ whiteSpace: "pre-wrap" }}>{" "}</h1>;
    }
    
    ReactDOM.render(<App />, document.getElementById("root"));
    h1 { /* so we can see the h1 */
      background-color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="root"></div>