2

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?

ksav
  • 20,015
  • 6
  • 46
  • 66
nardoyala
  • 77
  • 2
  • 10
  • 2
    Does this answer your question? [What is {this.props.children} and when you should use it?](https://stackoverflow.com/questions/49706823/what-is-this-props-children-and-when-you-should-use-it) – ksav Mar 15 '20 at 01:50

1 Answers1

-1

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,
      },
    })
  })
EliteRaceElephant
  • 7,744
  • 4
  • 47
  • 62
  • Thank you so much! I checked `gatsby-config.js` and `gatsby-node.js` files and after some time trying to understand what I was reading I finally found how was that prop been passed. I'm using the Gatsby Advanced Starter by the way. Maybe I shouldn't have gone with something called "advanced", but I could't help it. – nardoyala Mar 15 '20 at 18:20