Reputation: 3831
I'm writing a small blog app with Gatsby (React and Graphql). There's a small thing that I don't quite understand. Here is my blog page code:
const Blog = ({ data }) => {
console.log(data)
return (
<Layout>
<h1>Blog</h1>
{data.allMarkdownRemark.edges.map(({ node }) => (
<div key={node.id}>
<h3>{node.frontmatter.title}</h3>
</div>
))}
</Layout>)
}
export default props => (
<StaticQuery
query={graphql`
query {
allMarkdownRemark {
totalCount
edges {
node {
id
frontmatter {
title
path
date
tags
}
}
}
}
}
`}
render={ data => <Blog data={data} {...props} />}
/>
)
What I'm confused by is this line:
{data.allMarkdownRemark.edges.map(({ node }) => (
my question is, why does this return an error:
{data.allMarkdownRemark.edges.map( node => (
Why are the curly brackets needed? The confusion comes from the fact that we're already receiving the list from markdownremark.edges, so why do we have to specify that it's dynamically generated content again? Is it a graphql thing?
It would be great to know the answer, thanks in advance.
Upvotes: 3
Views: 2744
Reputation: 8223
If I understand well, then you do not know why curly braces is needed around the node. It is an es6 syntax called destructuring. When the function parameter has a property you can extract that property in this way.
({ node }) => ( <div key={node.id}> // you can use the node here
It is equivalent with.
(data) => ( <div key={data.node.id}> // you must use the property thought the parameter
You can read more about it here: http://es6-features.org/#ObjectMatchingShorthandNotation
Upvotes: 0
Reputation: 1507
It is Javascript Destructuring Feature...
let test = [{name : 'sathish'},{name : 'steve'}];
//here you are access directly with destructuring es6 feture
test.map(({name})=>{console.log(name)}
test.map((fullObj)=>{console.log(fullObj.name)})
Refere this -> js destructuring...
Upvotes: 0
Reputation: 681
This is Object Destructuring and Property Shorthand feature.
1.) What will happen when using curly braces.
.
-> when you iterate using map on edges list you get the edge object in your map function, at the same time you have explicitly mention to destruct node property from edge object.
{data.allMarkdownRemark.edges.map(({ node }) => (
<div key={node.id}>
<h3>{node.frontmatter.title}</h3>
</div>
))}
2.) What will happen when curly braces not use
.
-> when you iterate through map on edges list you will get edge object as a parameter inside the function. in this case, you have to access node property explicitly.
{data.allMarkdownRemark.edges.map( edge => (
<div key={edge.node.id}>
<h3>{edge.node.frontmatter.title}</h3>
</div>
))}
Ref : Destructing Feature Hope so it will clear your doubt..
Upvotes: 2