All Articles

Using State & The Component Lifecycle in Gatsby.js

Using React State and the Component Lifecycle componentDidMount(), constructor(), and other event handlers in GatsbyJS pages isn’t immediately obvious.

A typical gatsby.js page component uses and arrow function to generate a page component with data coming from a graphQL query.

import React from "react"
export default ({ data }) => (
    <div>
      <h1This is a typical gatsby component</h1>
    </div>
)

By extending the React.component as a class of our page template, we can handle state within the GatsbyJS page component.

class ComponentName extends React.Component

We can then call the constructor, set our event handler and call the render function.

class ComponentName extends React.Component  {
    constructor(props) {
    super(props);
    this.state = { showComponent: true };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ showComponent: !this.state.showComponent });
  }

  render() {
    const { data } = this.props;
    return (
        <button onClick={this.handleClick}>
         {this.state.showComponent ? 'ON' : 'OFF'}
        <button/>
    )
  }
}

Putting it all together we can populate data from a graphQL query: passed down as props.

class ComponentName extends React.Component  {
    constructor(props) {
    super(props);
    this.state = { showComponent: true };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState({ showComponent: !this.state.showComponent });
  }

  render() {
    const { data } = this.props;
    return (
        <>
        <h1{data.name}</h1>
        <button onClick={this.handleClick}>
         {this.state.showComponent ? 'ON' : 'OFF'}
        <button/>
    )
  }
}

ComponentName.propTypes = {
  data: PropTypes.shape({
    markdownRemark: PropTypes.shape({
      frontmatter: PropTypes.object,
    }),
  }),
}



export default ComponentName
export const ComponentNameQuery = graphql`
  query ComponentName($id: String!) {
    markdownRemark(id: { eq: $id }) {
      frontmatter {
        name
      }
    }
  }
`