Skip to content Skip to sidebar Skip to footer

Onepage With Gatsby Js And Contentful, How To Import My First Simple String

I am trying to useStatic Query and GraphQL to get a simple title from Contentful, pass it to state and then show in the render. I cant make it work. I am attaching an image showin

Solution 1:

If you're writing a page component as a class, you don't need to use the UseStaticQuery, you can use the simple PageQuery for this purpose. To loop through arrays, the map() method works as well.

UPDATE

importReact, { Component } from'react';
import { graphql } from'gatsby';

exportdefaultclassTestextendsComponent {
  render() { 

  const { edges } = this.props.data.test;

    return (
     <div>
      {edges.map(({ node: itemFromContentful }) => (
          <h1>{itemFromContentful.section1Title}</h1><h1>{itemFromContentful.section2Lead}</h1>
          {documentToReactComponents(section1Text.json)}
      ))}
     </div>
    );
  }
}

exportconst query = graphql`
{
  test:allContentfulHomePage(limit: 1) {
    edges {
      node {
        section1Title
      }
    }
  }
}
`

Whats happening:

  1. The GraphQL query you're using is bringing the data you want from the Contentful;
  2. The React Stateful Component (class Test) is receiving all the data available from the query as a prop;
  3. We're accessing this data on the render() method using the destructing assignment;
  4. we're accessing the data nodes through the map method (the one I suggested you to take a look;
  5. The curly braces into the JSX allows you to use JS to manipulate what you want - In this case, to render the information.

Post a Comment for "Onepage With Gatsby Js And Contentful, How To Import My First Simple String"