2

I am using React/JSX, I want to add multiple whitespaces depending on a condition, here is the element <h1>HELLO WORLD</h1>, I want to achieve effect like this in the broswer

HELLO         WORLD

I tried using {' '}, but it only add a single whitespace no matter how many spaces typed inside the quotes, for example, <h1>HELLO {" "} WORLD</h1> still got

HELLO WORLD

I know we could use multiple &nbsp; like <h1>HELLO&nbsp;&nbsp;&nbsp;&nbsp;WORLD</h1>, but I need to calculate the number of whitespaces like &nbsp; * my_variable so I can't hardcode it.

How can I do this?

john
  • 29
  • 3

2 Answers2

1

Update: As @kangasta pointed out in the comments, you can use the repeat() function on a \u00a0, the unicode value of NO-BREAK SPACE.

{'\u00a0'.repeat(spaces)}

Original: You could create an array of n items, map() over them, and let it return a <React.Fragment> with a &nbsp; inside it:

{[...Array(spaces)].map(e => <React.Fragment>&nbsp;</React.Fragment>)}

Demo showing both solutions mentioned above, press the button to increase the number of spaces.

const { useState } = React;

const Example = () => {

    const [spaces, setSpaces] = useState(5);

    return (
        <div>
            <h1>{'Example'}</h1>
            
            {/* str repeat */}
             <h3>
                {'Hello'}
                {'\u00a0'.repeat(spaces)}
                {'World'}
            </h3>
            
            {/* Array + Map */}
            <h3>
                {'Hello'}
                {[...Array(spaces)].map(e => <React.Fragment>&nbsp;</React.Fragment>)}
                {'World'}
            </h3>
            
            <button onClick={() => setSpaces(p => p + 1)}>Increase spacing</button>
        </div>
    )
}
ReactDOM.render(<Example />, document.getElementById("react"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>
0stone0
  • 34,288
  • 4
  • 39
  • 64
1

The HTML produced by your React app includes the white-space. You can verify this by inspecting the element with your browsers developer tools. The white-space is collapsed by the browser when rendering the page, so this is more of a HTML/CSS than a React feature.

To render white-space inside an element without them being collapsed, you could use white-space CSS property with pre or pre-wrap value.

.preserve-white-space {
  white-space: pre;
}
<h1 class="preserve-white-space">HELLO          WORLD</h1>
kangasta
  • 642
  • 7
  • 17