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
like <h1>HELLO WORLD</h1>
, but I need to calculate the number of whitespaces like * my_variable
so I can’t hardcode it.
How can I do this?
2
Answers
You could create an array of n items,
map()
over them, and let it return a<React.Fragment>
with a
inside it: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
orpre-wrap
value.