skip to Main Content

Whenever i am trying to run below line of code, its not executing ‘
‘ as break line but actually executing it as string.

const firstFiveLetters = chartData.centerText.slice(0, 5);
const remainingLetters = chartData.centerText.slice(5);

// Return the text with line break after the first five letters
return `${firstFiveLetters}<br>${remainingLetters}`;

I am expecting a line break after the execution of first but its not executing above html element.

2

Answers


  1. I think that the problem is that you are not rendering firstFiveLetters as HTML, so it is detected as a string;

    const firstFiveLetters = chartData.centerText.slice(0, 5);
    const remainingLetters = chartData.centerText.slice(5);
    //Render the variable with the desired content as HTML using __html:
    const htmlString = `${firstFiveLetters}<br>${remainingLetters}`;
    return { __html: htmlString };
    
    Login or Signup to reply.
  2. Your method return string, not react elements, thats why line-break renders as string. React way to format text would look something like this:

    const firstFiveLetters = chartData.centerText.slice(0, 5);
    const remainingLetters = chartData.centerText.slice(5);
    
    return (<>{firstFiveLetters}<br />{remainingLetters}</>);
    

    as you can see in this case we will return React node, not string. You can even create component for this kind of formatting.

    function LineBreakTextFormat({ text, first = 5 }) {
      const start = text.slice(0, first);
      const remaining = text.slice(first);
      return (
        <>
         {start}
         {!!remaining && <><br />{remaining}</>}
        </>
      );
    }
    
    // And then use it like this
    <LineBreakTextFormat text={chartData.centerText} first={5} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search