Search code examples
reactjstypescriptstring-interpolationpreact

Typescript/React `<span>Text</span>`only writes out the text and not element


I have this quite simple function that splits a string and puts in a styles span in the middle as i want some styled text there it looks like this

splitAndApplyStyledContent(content: string, textType: string, separator: string) {
  const splittedContent = content.split(separator);

  switch (textType) {
    case 'Info':
      return [
        splittedContent[0],
        `<span className="styled-text">${this.getString(Name)}</span>`,
        splittedContent[1],
      ];
    default:
      return content;
  }
}

The problem here is that when i call it in my tsx file like

{ props.myStringManager.splitAndApplyStyledContent(props.myStringManager.getString(infoContent), "Info" , '{X}')}

it will also write out the <span className="styled-text"> </span> part instead of making it into an element and applying the style to it

To clarify this function is inside a class that looks like export default class LocalizationsManagerso not a component or anything like it it is also an .ts file and no .tsx


Solution

  • Return a valid JSX, not an array:

    ...
    return (
      <>
        {splittedContent[0]}
        <span className='styled-text'>{this.getString(Name)}</span>
        {splittedContent[1]}
      </>
    )
    ...