Home > Net >  How to break lines in received JSON data
How to break lines in received JSON data

Time:06-28

I am using a poetry API in my application and when I receive the poem lines in JSON, they are formatted as:

lines: Array(14) 0: "I met a traveller from an antique land" 1: "Who said: Two vast and trunkless legs of stone" 2: "Stand in the desert...Near them, on the sand," 3: "Half sunk, a shattered visage lies, whose frown," 4: "And wrinkled lip, and sneer of cold command," 5: "Tell that its sculptor well those passions read" 6: "Which yet survive, stamped on these lifeless things," 7: "The hand that mocked them, and the heart that fed:" 8: "And on the pedestal these words appear:" 9: "'My name is Ozymandias, king of kings:" 10: "Look on my works, ye Mighty, and despair!'" 11: "Nothing beside remains. Round the decay" 12: "Of that colossal wreck, boundless and bare" 13: "The lone and level sands stretch far away." length: 14

I'm having trouble displaying each item in the JSON array as a new line when I output it onto my page.

Currently I have a component that maps each returned poem into a card with the respective author, title, and lines of the poem

poem.map(item => {
  let author = item.author;
  let title = item.title;
  let lines = item.lines;
  if (author != undefined && title != undefined) {
    return (
      <>
        <div className="viewer">
          <div className="author">{author}</div>
          <div className="title">{title}</div>
          <div className="lines">{lines}</div>
        </div>
      </>
    );
  }
});

What ends up getting displayed on my webpage is each line after the next without any line breaks between them.

CodePudding user response:

You can try applying the css display: block; to the viewer and that will make each div child of viewer take up the full width of the parent

CodePudding user response:

If you put text in a <div>, it won't have line breaks by default. To get line breaks, you'll have to either put each line in its own block element (like <div>) or insert a <br/> tag between each line.

Here's an example of each. https://jsfiddle.net/bdLru78c/

CodePudding user response:

In your current code, lines of poem are displayed based on the original JSON data without any line breaks I think we can solve this problem like below

<div className="lines">
    {lines.map((line)=> {
       <div>{line}</div>
    })}
 </div>

Also, you can use for statement for this Please let me know if you have problems

  • Related