What is the children variable in Gatsby? How could I assign that to another component?

Viewed 368

I'm trying to make a small blog with Gatsby, but there is something in my index.jsx that I'm not able to understand.

There is a variable that is defined like this:

const { children } = this.props;

When rendering, that represents the lastest post. But I can't figure out where I assign that prop. For example, when I'm rendering a header component I pass the props like this:

<Header myProps="someValue" />

But, How could I do that with the index? Is not in the index where you call all your components with their props?

This is my index.jsx file:

import React from "react";
import Helmet from "react-helmet";
import Navigation from "../components/Navigation";
import config from "../../data/SiteConfig";
import "../styles/main.scss";

export default class MainLayout extends React.Component {
  render() {
    const { children } = this.props;
    return (
      <>
        <Helmet>
          <meta name="description" content={config.siteDescription} />
          <html lang="en" />
        </Helmet>
        <Navigation menuLinks={config.menuLinks} />
        <main>{children}</main>
      </>
    );
  }
}

See? I use { children } in the index, but how does Gatsby know what is that variable if I never pass the prop?

1 Answers

Gatsby allows to query for content i.e. children components in various ways. You did not specify what starter or theme you are using which might be important for your question.

See? I use { children } in the index, but how does Gatsby know what is that variable if I never pass the prop?

Some plugin or theme inside your code base is providing the children props to your index component. Go through your gatsby-config.js and gatsby-node.js and look for components that inject data.

This tutorial explains how to provide data to components. As an example, one way to pass data as props to a template component is using the node API:

// gatsby-node.js

  result.data.allMarkdownRemark.edges.forEach(({ node }) => {
    createPage({
      path: node.fields.slug,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        // Data passed to context is available
        // in page queries as GraphQL variables.
        slug: node.fields.slug,
      },
    })
  })
Related