tommyd456 tommyd456 - 2 months ago 13
Javascript Question

Using map in React to create components

I have this code that returns a component:

const Test = ({places}) => (
<div>
{places.map(place => (
<div className="location" key={place.slug}>
<div className="photo" style={ { backgroundImage: "url(" + place.src + ")" } }></div>
<h2>{place.name}</h2>
</div>
))}
</div>
);


but I'm getting confused between
(
and
{
brackets. I'm actually trying to get rid of the outer
<div>
tags but it doesn't seem to work when I use:

const Test = ({places}) => (
{places.map(place => (
<div className="location" key={place.slug}>
<div className="photo" style={ { backgroundImage: "url(" + place.src + ")" } }></div>
<h2>{place.name}</h2>
</div>
))}
);

Answer

You need to use that div, Reason is you are using map to create the elements Dynamically and map will return an array and we can not return more than one element, so you need to wrap them in a div.

A React component can't return multiple elements, but a single JSX expression can have multiple children, so if you want a component to render multiple things you can wrap it in a div.

Don't forget that the its a functional component, Functions always take in a number of parameters and always return exactly one value.

Update:

If you want to do some calculation or want to define variables inside Functional component then write the component in this way:

const Test = ({places}) => {   //use {
   let a = 1, b = [1,2,3,4];
   b.forEach(el => console.log(el));

   return(  //use return to return the html elements
      <div>
          hello world!!!
          //other elements
          ......
      </div>
   )
};