skip to Main Content

I need to format text based on provided text specific style using react js. e.g:

Here i have observed one thing like, if i pass text with some variable e.g:

const text = "\nBubble\nAir\nSKY";
 <myComponent variableText={text} />

Then inside my component when i inspect the passed data it shows like below:

"Bubble
 Air
 SKY"

If i get data like in this type of format, It is working fine for me. But when i direct pass the string text in my component like below:

<myComponent text="nBubblenAirnSky" />

So after inspect in the component passed text it shows same like string.
e.g: "nBubblenAirSKY";

How do we first get the string value as text in React js?

Need help

3

Answers


  1. as i understood your component like this :

     const MyComponent = ({ text }) => {
          return (
            <div>
              {text.split('n').map((item, index) => (
                <span key={index}>
                  {item}
                  <br />
                </span>
              ))}
            </div>
          );
        };
    

    You can modify your component with your specific splitter do you want or you can use just an method like this :

    const formatText = (text) => {
      return text.split('n').map((item, key) => (
        <span key={key}>
          {item}
          <br />
        </span>
      ));
    };
    
    Login or Signup to reply.
  2. If use this as Direct String it will be use as regular String , if you want to break the string you can use a formatter

    const formattedText = text.split('\n').join('n');
    

    now in your Component you can use as you wish

        <div style={{ whiteSpace: 'pre-line' }}>
          {formattedText}
        </div>
    

    then when you use it you can pass the string
    const text = "nBubblenAirnSky";

    Login or Signup to reply.
  3. const MyComponent = ({ text }) => {
      // Replace n with <br> tags for HTML rendering
      const formattedText = text.replace(/\n/g, '<br>');
    
      return (
        <div dangerouslySetInnerHTML={{ __html: formattedText }} />
      );
    };

    Try to use dangerouslySetInnerHTML

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search