skip to Main Content

I loop through an Array of objects in ReactJS where I use map function to loop through each Object. So Can i use
tag to separate each objects in next line. I tried to put a
tag at the end of the loop but it does’nt work. Let me know what the correct way of using it. The code is as follows. Thanks in Advance!

import React from 'react'

const items = [{
  name: "EVC",
  price: 300
},{
  name: "JVN",
  price: 500
}]

const App = () => {
  return (
    <div className='items'>
      {items.map(item=> item.name + item.price+"<br>")}
    </div>
  )
}

export default App

2

Answers


  1. When you concentrate values, React escapes html tags for saftety. In your case <br> is treated as plain text, not html tag. If you really wanted to use it the way as in provided example, there is special prop dangerouslySetInnerHTML to output raw html.
    However, it’s better to add <br> directly using <> (shortcut for React.Fragment) to wrap your item data inside map. You can use React.fragment when you want to group items without rendering extra element in the DOM:

    import React from 'react'
    const items = [
      {
        name: "EVC",
        price: 300
      },
      {
        name: "JVN",
        price: 500
      }
    ];
                
    const App = () => {
      return (
        <div className="items">
          {items.map((item) => (
            <>
              {item.name} {item.price} <br />
            </>
          ))}
        </div>
      );
    };
    export default App
    
    Login or Signup to reply.
  2. Avoid using <br> for space between paragraphs whenever you can.

    const App = () => {
      return (
        <div className='items'>
          {
          items.map((item, index) => {
           return(
            <div key={item + index} className="itemContainer">
                <p className="paragraph">{item.name + " " + item.price}</p> {/*Empty quotes are for space between the name and price*/}
            </div>
    )
    })
          }
        </div>
      )
    }
    
    

    <p></p> has it’s own line break so use it instead and use margin in your styles for more space if you see fit.

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