skip to Main Content

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?

2

Answers


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

    const { useState } = React;
    
    const Example = () => {
    
        const [spaces, setSpaces] = useState(5);
    
        return (
            <div>
                <h1>{'Example'}</h1>
                <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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search