Reputation: 5729
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?
EDIT: After finding out about destructuring assignment from the answers I read the following article about how to use it in a function and it became very clear to me. https://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/
Upvotes: 1
Views: 397
Reputation: 1194
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.
Upvotes: 1
Reputation: 2052
The function argument uses destructuring assignment to extract values from an object.
The braces around JSX are here to keep the indentation clean.
You can do this:
return <div>
lol
</div>
But you can't do this:
return
<div>
lol
</div>
So, to keep the indentation of JSX clean, you have to wrap the markup with braces.
Upvotes: 1