javascriptreactjsjsx

Why we should use {} in return statment


I'm new in react and I have question:

Why I should use curly braces inside return statement?

Example code:

import React from 'react';
import Hobbies from './Hobbies';

const HobbyList = () => {

    const hobbies = ["Surfing", "Rock climbing", "Mountain biking", "Breakdancing"];
    return (
        <div>
           { hobbies.map(hob => <Hobbies hobbies={hob}/>)}
        </div>
    );
};

export default HobbyList;

Solution

  • Somehow the code needs to be separated from HTML tags and this is the way you can run JavaScript code inside your return statement.

    As the documentation states:

    It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

    Suggested documentation to read:

    1. Introducing JSX
    2. Embedding Expressions in JSX