4

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>
  ))}
);
3
  • Where do you use Test? maybe you can use it as a function instead of a Component Commented May 8, 2017 at 21:53
  • I was actually wondering that! Just getting to grips with React. I have it outside my class at the moment but should it be part of a class method? Commented May 9, 2017 at 10:57
  • It does not matter where the function is, but how you use it. Post the code where you use Test and we'll see if it can be replaced. Commented May 9, 2017 at 14:38

1 Answer 1

2

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>
   )
};
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks. The problem is that the extra <div> has a display:block by default.
i think default style you can override by defining the style on that div. like this: <div style={{display: 'some value'}}>
Got it sorted. Thanks
On a sidenote: how do I put a variable within the inside function?
check the updated answer, you need to write the component in that way :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.