skip to Main Content

My <div> contains a message from a message array, but I can’t show it in a new line in UI. It all comes in the same line.

enter image description here

My code is:

<div className="md:container xl:mx-auto  space-y-1  border-zinc-800 rounded border-2 w-30 h-60 bg-blue-300">
      <h2 className="font-serif text-xl">{_message.map((Message) => Message)}</h2>
</div>

I want my all new messages come in new line

3

Answers


  1. Add the whitespace-pre class to the <h2>:

    <div className="md:container xl:mx-auto  space-y-1  border-zinc-800 rounded border-2 w-30 h-60 bg-blue-300">
      <h2 className="font-serif text-xl whitespace-pre">{_message.map((Message) => Message)}</h2>
    </div>
    

    This way, if the text contains line-feeds, they are preserved visually.

    See: Whitespace – Tailwind CSS

    Login or Signup to reply.
  2. You have _messages array and you are placing everything inside the h2. that is why it looks like this

    item1 item2 item3

    Instead for each array item, you should have h2 or better way, you should have a separate component.

     // this is simplified. you might need to pass more props. maybe username etc
     {_message.map((message) => <MessageComponent content={message} />)}
    

    MessageComponent should be like this:

    const MessageComponent=({content})=>{
       return (
           <div className="flex flex-col" >{content}</div>
        )
    }
    
    Login or Signup to reply.
  3. You are directly rendering the text per item in the _message array. Text is treated as an inline element. You could wrap the message text in block elements like div or p to show each item in a new line. Something like this:

    <div className="md:container xl:mx-auto  space-y-1  border-zinc-800 rounded border-2 w-30 h-60 bg-blue-300">
        <h2 className="font-serif text-xl">{_message.map((Message) => <div>Message</div>)}</h2>
    </div>
    

    As @Yilmaz suggests, you could also render a custom component and style it based on your requirements.

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