droledenom
droledenom

Reputation: 225

Use of curly braces in React

I am trying to learn React. I am having trouble with the use of curly braces. Use of curly brace makes difference between JSX and JS In the code below, Curly Brace 1 says "now it is JS". Why is there curly brace 2 ? It is already inside a curly brace zone ?

var React = require('react');
var ReactDOM = require('react-dom');

var MyCompClass = React.createClass({ // open curly brace 1
  render: function () { // open curly brace 2
    return <h1>Hello</h1>;
  }
});

ReactDOM.render(
    <MyCompClass />, 
    document.getElementById('app')
);

A second quick question :

ReactDOM.render(
        <MyCompClass />, 
        document.getElementById('app')
    ); 

why do .render() need HTML marks around MyComponentClass ?

Thank you for your help !

Upvotes: 1

Views: 5826

Answers (2)

burak
burak

Reputation: 4064

You are calling React.createClass method with object parameter. The first curly braces is the syntax of standard javascript object. In this object there is a property called as 'render'. This render attribute could be a function, so the second curly braces are the scope of javascript function syntax.

Also, the HTML marks in your render method is your React component and this is JSX syntax.

So, the following documentations may be helpful:

  1. React Without ES6
  2. Introducing JSX
  3. React Without JSX

Edit: Also, I realized that React props usage may cause confusion for you. In react, the syntax of props usage again with curly braces but this is used to provide dynamic binding for your components. By using this syntax, your component will be able to update your html, if the value of your prop is changed. The following is the example of this case:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

For more detailed information, please examine the related React document for Component and Props usage.

Upvotes: 1

OurOwnOwl
OurOwnOwl

Reputation: 354

Curly brace 2 contain the render() function's body.

Curly brace 1... actually also contains function's body, where the function is React.createClass(). This function takes as an argument an object, created with curly braces 1, containing functions and variables (in this case this object contains only render() method).

The truth is, that in this example the only JSX elements are<h1>Hello</h1>; and <MyCompClass />. They use JSX syntax, while with pure JS the createElement() and appendChild() DOM functions would be required.

Upvotes: 0

Related Questions