Home > Enterprise >  No spaces when mapping every character of a string (ReactJS)
No spaces when mapping every character of a string (ReactJS)

Time:10-18

I have been trying to put some animation on a title.. (using ReactJs)

The issue I have is that my Array.map() won't display my spaces from my string:

Prop 'title' = "Header Right Here!!"

const TitleAnimation = ({title}) => {
    const titleArray = title.split("");
    console.log(titleArray);
    // logs all characters in an array, including spaces

    return (
        <Wrapper className="text-6xl">
            {titleArray.map((character, index) => {
                return (
                    <span key={index}>{character}</span>
                )
            })}
        </Wrapper>
    );
}

Instead of having multiple spans returning "Header Right Here", it returns "HeaderRightHere"

Did I do something wrong?

Thanks in advance!

CodePudding user response:

White spaces are collapsed by default in spans. You can use the CSS property white-space with the value pre in order for your span to preserve the spaces.

span {
  white-space: pre;
}

(You might or might not want to set that globally)

You can find more details about the white-space property here: https://css-tricks.com/almanac/properties/w/whitespace/

CodePudding user response:

Please refer to the following code

import React from 'react';

const App = () => {
  const title = 'Header Right Here!!';
  const titleArray = title.split(' ');
  const renderTitle = () => {
    return titleArray.map((title, index) => {
      return (
        <span>
          {title}
          {` `}
        </span>
      );
    });
  };
  return <div>{renderTitle()}</div>;
};
export default App;

Note : Each element in the array is wrapped in a span

  • Related