Muhammad Raihan Muhaimin Muhammad Raihan Muhaimin - 3 months ago 17
React JSX Question

Understand es6 and jsx in react

I am going through the official redux tutorial.

http://redux.js.org/docs/basics/UsageWithReact.html


In the file

components/Link.js
have the following code

import React, { PropTypes } from 'react'

const Link = ({ active, children, onClick }) => {
if (active) {
return <span>{children}</span>
}

return (
<a href="#"
onClick={e => {
e.preventDefault()
onClick()
}}
>
{children}
</a>
)
}

Link.propTypes = {
active: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func.isRequired
}

export default Link


What I am wondering why function link accepting the variable surrounded by curly braces. Secondly, the return statement inside the if block has the
span
jsx tag without the braces but the secondly the return statement outside the if block with the
<a>
tag has a braces. Can anyone explains why?

Answer

That's a stateless function, you can define react classes as plain JS functions when they don't have state and life-cycle methods

The curly braces are placed in there to use an amazing es6 feature called Destructuring.

Basically using es6 that's the same as doing:

const Link = (props) => {
   const { active, children, onClick } = props;
   ...

And without using ES6 it would be the same as doing:

const Link = (props) => {
   const active = props.active;
   const children = props.children;
   const onClick = props.onClick;
   ....

About the return you use brackets when your jsx elements have more then 1 line.

Comments