gatsby#StaticQuery TypeScript Examples

The following examples show how to use gatsby#StaticQuery. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResponsiveImage.tsx    From pola-web with MIT License 6 votes vote down vote up
ResponsiveImage: React.FC<IResponsiveImage> = function ({ imageSrc }) {
  return (
    <StaticQuery
      query={graphql`
        query {
          images: allFile(filter: { sourceInstanceName: { eq: "images" } }) {
            edges {
              node {
                extension
                relativePath
                childImageSharp {
                  fluid {
                    ...GatsbyImageSharpFluid
                  }
                }
              }
            }
          }
        }
      `}
      render={(data) => {
        try {
          const image = data.images.edges.find((imageEdge: any) => imageEdge.node.relativePath === imageSrc);
          return renderImage(image);
        } catch {
          console.error(`Cannot load image "${imageSrc}"`);
          return;
        }
      }}
    />
  );
}
Example #2
Source File: Footer.tsx    From defund12.org with MIT License 6 votes vote down vote up
/**
 * The site footer, containing issue request and contact information.
 * @return {React.ReactNode}
 */
export default function Footer(): JSX.Element {
  return (
    <StaticQuery
      query={graphql`
        query FooterQuery {
          siteConfig {
            footerTextPr
            footerTextInstructions
            contactEmailFooter
          }
        }
      `}
      render={(data: { siteConfig: FooterProps }) => (
        <_Footer {...data.siteConfig} />
      )}
    />
  );
}
Example #3
Source File: Header.tsx    From defund12.org with MIT License 6 votes vote down vote up
/**
 * The site header, containing the banner and introduction.
 * @return {JSX.Element}
 */
export default function Header(): JSX.Element {
  return (
    <StaticQuery
      query={graphql`
        query HeaderQuery {
          siteConfig {
            siteTitle
            subtitle
          }
        }
      `}
      render={(data: { siteConfig: HeaderProps }) => (
        <_Header
          siteTitle={data.siteConfig.siteTitle}
          subtitle={data.siteConfig.subtitle}
        />
      )}
    />
  );
}
Example #4
Source File: letters.tsx    From defund12.org with MIT License 6 votes vote down vote up
/**
   * React render method.
   * @return {React.ReactNode} the rendered component
   */
  render(): React.ReactNode {
    return (
      <StaticQuery
        query={graphql`
          query LetterPageQuery {
            siteConfig {
              letterPageHeader
            }
          }
        `}
        render={(data: { siteConfig: LettersPageConfig }) => {
          const header = (
            <span
              dangerouslySetInnerHTML={{
                __html: DefundUtils.markdownToHTML(
                  data.siteConfig.letterPageHeader
                ),
              }}
            ></span>
          );

          return (
            <Layout>
              <TemplateList layout="letter" header={header} />
            </Layout>
          );
        }}
      />
    );
  }
Example #5
Source File: image.tsx    From vhealth-gatsby with MIT License 6 votes vote down vote up
Image = (props: { filename: any; alt: string | undefined }) => (
  <StaticQuery
    query={graphql`
      query {
        images: allFile {
          edges {
            node {
              relativePath
              name
              childImageSharp {
                fluid(maxWidth: 600) {
                  ...GatsbyImageSharpFluid
                }
              }
            }
          }
        }
      }
    `}
    render={data => {
      const image = data.images.edges.find(n => {
        return n.node.relativePath.includes(props.filename)
      })
      if (!image) {
        return null
      }

      //const imageSizes = image.node.childImageSharp.sizes; sizes={imageSizes}
      return <Img alt={props.alt} fluid={image.node.childImageSharp.fluid} />
    }}
  />
)
Example #6
Source File: layout.tsx    From website with MIT License 6 votes vote down vote up
render() {
		const { title, narrowLayout } = this.props;
		return (
			<React.Fragment>

				<StaticQuery
					query={query}
					render={(data) => (
						<Helmet titleTemplate={data.site.siteMetadata.titleTemplate} defaultTitle={data.site.siteMetadata.defaultTitle}>
							{title && <title>{title}</title>}
							<meta property='og:type' content='website' />
							<meta property='og:title' content={`${title ? `${title} - ` : ''}${data.site.siteMetadata.defaultTitle}`} />
							<meta property='og:site_name' content='DataCore' />
							<meta property='og:image' content={`${data.site.siteMetadata.baseUrl}/media/logo.png`} />
							<meta property='og:description' content={data.site.siteMetadata.defaultDescription} />
							<link id='defaultThemeCSS' rel='stylesheet' type='text/css' href={withPrefix('styles/semantic.slate.css')} />
							<link rel='stylesheet' type='text/css' href={withPrefix('styles/easymde.min.css')} />
							<script src={withPrefix('styles/theming.js')} type='text/javascript' />
							<script src={withPrefix('polyfills.js')} type='text/javascript' />
						</Helmet>
					)}
				/>
				<TopMenu narrowLayout={narrowLayout}>
					{this.props.children}
				</TopMenu>
			</React.Fragment>
		);
	}
Example #7
Source File: Layout.tsx    From defund12.org with MIT License 5 votes vote down vote up
// todo: add separate template for email and for index/404 so prop types are more clearly defined
/**
 * The site layout, which contains elements to
 * place in <head> through React Helmet.
 * @param {OptionalLayoutProps} props
 *    pass in child elements, page title, and meta
 * @return {JSX.Element}
 */
export default function Layout(
  props: React.PropsWithChildren<OptionalLayoutProps>
): JSX.Element {
  return (
    <StaticQuery
      query={graphql`
        query LayoutQuery {
          siteConfig {
            siteTitle
            meta
            logoUrl
            faviconUrl
            metaPreviewUrl
            googleApiKey
          }
        }
      `}
      render={(data: { siteConfig: LayoutProps }) => (
        <_Layout
          {...data.siteConfig}
          pageTitle={
            props.pageTitle ? props.pageTitle : data.siteConfig.siteTitle
          }
          meta={props.meta ? props.meta : data.siteConfig.meta}
          logoUrl={
            props.metaQueryString
              ? data.siteConfig.metaPreviewUrl +
                props.layout +
                "?" +
                props.metaQueryString
              : data.siteConfig.logoUrl
          }
        >
          {props.children}
        </_Layout>
      )}
    />
  );
}
Example #8
Source File: TemplateList.tsx    From defund12.org with MIT License 5 votes vote down vote up
/**
 * The main container for email links, including filtering.
 * @param {string} layout the kinds of templates to show - email or letter
 * @return {React.ReactNode} The rendered email component,
 * with data from GraphQL.
 */
export default function TemplateList({
  layout,
  header,
}: TemplateListParams): JSX.Element {
  return (
    <StaticQuery
      query={graphql`
        query TemplateListQuery {
          allMarkdownRemark(
            filter: {
              frontmatter: { permalink: { ne: null }, name: { ne: null } }
            }
          ) {
            nodes {
              frontmatter {
                permalink
                name
                city
                state
                layout
              }
            }
          }
        }
      `}
      render={(data: { allMarkdownRemark: { nodes: Array<RemarkNode> } }) => {
        // extract the email metadata from the nodes collected from markdown
        const allNodes = data.allMarkdownRemark.nodes;
        const allTemplateMetadata = allNodes
          .map((node: RemarkNode) => node.frontmatter)
          .filter((v) => v.layout === layout);

        const stateGroupedTemplates = groupTemplateMetadataByState(
          allTemplateMetadata
        );

        return (
          <>
            {header && <header>{header}</header>}
            <_TemplateList stateGroupedTemplates={stateGroupedTemplates} />
          </>
        );
      }}
    />
  );
}
Example #9
Source File: announcement.tsx    From website with MIT License 5 votes vote down vote up
Announcement = () => {
	const [readyToAnnounce, setReadyToAnnounce] = React.useState(false);
	const [dateNow, setDateNow] = React.useState(new Date());
	const [dismissAnnouncement, setDismissAnnouncement] = useStateWithStorage(
		'dismissAnnouncement',	/* cookie name */
		undefined, /* initial value */
		{
			rememberForever: true,
			onInitialize: () => setReadyToAnnounce(true)
		} /* storage options */
	);

	// To avoid rendering and then hiding an announcement that was previously dismissed,
	//	wait for cookie retrieval before rendering the message in the first place
	if (!readyToAnnounce) return (<></>);

	const query = graphql`
		query AnnouncementQuery {
		  allMarkdownRemark(
			limit: 1
			sort: {fields: [frontmatter___date], order: [DESC]}
			filter: {fields: {source: {eq: "announcements"}}}
		  ) {
			edges {
			  node {
				html
				frontmatter {
				  title
				  class
				  icon
				  date
				}
				excerpt(format:HTML)
			  }
			}
		  }
		}
	`;

	const render = ({ allMarkdownRemark }) => {
		const announcements = allMarkdownRemark.edges;
		if (announcements.length === 0) return (<></>);

		const announcement = announcements[0].node;
		const datePosted = new Date(announcement.frontmatter.date);
		if (dismissAnnouncement) {
			const dateDismissed = new Date(dismissAnnouncement);
			if (dateDismissed > datePosted) return (<></>);
		}

		const dateExpires = new Date(datePosted);
		dateExpires.setDate(datePosted.getDate()+DAYS_TO_EXPIRE);
		if (dateExpires < dateNow) return (<></>);

		const isExcerpt = announcement.html !== announcement.excerpt;

		return (
			<Message icon className={announcement.frontmatter.class ?? ''} onDismiss={() => setDismissAnnouncement(new Date())}>
				<Icon name={announcement.frontmatter.icon ?? 'info'} />
				<Message.Content>
					<Message.Header>{announcement.frontmatter.title ?? 'Message from the DataCore Team'}</Message.Header>
					<div dangerouslySetInnerHTML={{ __html: announcement.excerpt }} />
					{isExcerpt && (<Link to='/announcements/'>See details...</Link>)}
				</Message.Content>
			</Message>
		);
	};

	return (
		<StaticQuery query={query} render={render} />
	);
}
Example #10
Source File: episodes.tsx    From website with MIT License 5 votes vote down vote up
render() {
		return (
			<StaticQuery
				query={graphql`
					query {
						allEpisodesJson {
							edges {
								node {
									name
									description
									cadet
									episode_title
									episode
									total_stars
									episode_portrait {
										file
									}
									fields {
										slug
									}
								}
							}
						}
					}
				`}
				render={data => (
					<Layout title='Episodes'>
						<Item.Group>
							{data.allEpisodesJson.edges.map(({ node }, index) => (
								<Item key={index}>
									<Item.Image
										size="tiny"
										src={`${process.env.GATSBY_ASSETS_URL}${node.episode_portrait
												? node.episode_portrait.file.substr(1).replace('/', '_') + '.png'
												: 'crew_full_body_cm_empty_full.png'
											}`}
									/>

									<Item.Content>
										<Item.Header as="a" onClick={() => navigate(`/episode${node.fields.slug}`)}>
											{getEpisodeName(node)}
										</Item.Header>
										<Item.Meta>Total stars: {node.total_stars}</Item.Meta>
										<Item.Description>
											<p>{node.description}</p>
										</Item.Description>
									</Item.Content>
								</Item>
							))}
						</Item.Group>
					</Layout>
				)}
			/>
		);
	}
Example #11
Source File: Head.tsx    From gatsby-personal-site with MIT License 4 votes vote down vote up
Head: React.FC<HeadProps> = ({
  title,
  description,
  image,
  lang,
  keywords
}) => (
  <StaticQuery
    query={graphql`
      query {
        site {
          siteMetadata {
            title
            description
            siteUrl
            image
            googleSiteVerification
            author {
              name
            }
          }
        }
      }
    `}
    render={(data: StaticQueryData): React.ReactElement | null => {
      const metaDescription = description || data.site.siteMetadata.description
      const metaImage =
        data.site.siteMetadata.siteUrl +
        `${image || data.site.siteMetadata.image}`
      lang = lang || 'en'
      keywords = keywords || []
      useDynamicFavicon()

      return (
        <Helmet
          htmlAttributes={{
            lang
          }}
          title={title}
          titleTemplate={`%s | ${data.site.siteMetadata.title}`}
          meta={[
            {
              name: `description`,
              content: metaDescription
            },
            {
              property: `image`,
              content: metaImage
            },
            {
              property: `og:title`,
              content: title
            },
            {
              property: `og:description`,
              content: metaDescription
            },
            {
              property: `og:image`,
              content: metaImage
            },
            {
              property: `og:type`,
              content: `website`
            },
            {
              name: `twitter:card`,
              content: `summary`
            },
            {
              name: `twitter:creator`,
              content: data.site.siteMetadata.author.name
            },
            {
              name: `twitter:title`,
              content: title
            },
            {
              name: `twitter:description`,
              content: metaDescription
            },
            {
              name: `twitter:image`,
              content: metaImage
            },
            {
              name: `google-site-verification`,
              content: data.site.siteMetadata.googleSiteVerification
            }
          ].concat(
            keywords.length > 0
              ? {
                  name: `keywords`,
                  content: keywords.join(`, `)
                }
              : []
          )}
        />
      )
    }}
  />
)
Example #12
Source File: gauntlets.tsx    From website with MIT License 4 votes vote down vote up
render() {
		return (
			<StaticQuery
				query={graphql`
					query {
						allGauntletsJson {
							edges {
								node {
									gauntlet_id
									date
									jackpot_crew
									contest_data {
										featured_skill
										traits
									}
								}
							}
						}
						allCrewJson {
							edges {
								node {
									symbol
									name
									traits_named
									imageUrlPortrait
									max_rarity
									ranks {
										gauntletRank
									}
									base_skills {
										security_skill {
											core
											range_min
											range_max
										}
										command_skill {
											core
											range_min
											range_max
										}
										diplomacy_skill {
											core
											range_min
											range_max
										}
										science_skill {
											core
											range_min
											range_max
										}
										medicine_skill {
											core
											range_min
											range_max
										}
										engineering_skill {
											core
											range_min
											range_max
										}
									}
								}
							}
						}
					}
				`}
				render={data => (
					<Layout title='Gauntlets'>
						<Item.Group divided>
							{data.allGauntletsJson.edges.sort((a, b) => Date.parse(b.node.date) - Date.parse(a.node.date)).map(({ node }, index) => {
								const prettyDate = new Date(node.date).toDateString();
								const prettyTraits = node.contest_data.traits.map(t => trait_names[t]);
								const matchedCrew = data.allCrewJson.edges.filter(e => e.node.max_rarity > 3 && prettyTraits.filter(t => e.node.traits_named.includes(t)).length > 1).sort((a, b) => (prettyTraits.filter(t => b.node.traits_named.includes(t)).length - prettyTraits.filter(t => a.node.traits_named.includes(t)).length));
								return (
								<Item key={index}>
									<Item.Content>
										<Item.Header>
											{node.contest_data.traits.map(t => trait_names[t]).join("/")}/{SKILLS[node.contest_data.featured_skill]}
										</Item.Header>
										<Item.Meta style={{color: 'white'}}>{prettyDate}</Item.Meta>
										<Item.Description>
											<Grid stackable>
											{matchedCrew.map(({ node: crew }) => (
													<Grid.Column width={1} style={{textAlign: 'center'}}>
														<a href={`/crew/${crew.symbol}`}>
													<Image
													src={`${process.env.GATSBY_ASSETS_URL}${crew.imageUrlPortrait}`}
													size='tiny'
													alt={crew.name}
													style={{
														borderColor: CONFIG.RARITIES[crew.max_rarity].color,
														borderWidth: '1px',
														borderRadius: '4px',
														borderStyle: 'solid',
														marginLeft: 'auto',
														marginRight: 'auto'
													}}
												/>
												</a>
												{prettyTraits.filter(t => crew.traits_named.includes(t)).length == 3 ? '65%' : '45%'}
												<br />
												{crew.base_skills[node.contest_data.featured_skill] ? <img style={{width: '1em'}} src={`${process.env.GATSBY_ASSETS_URL}atlas/icon_${node.contest_data.featured_skill}.png`} /> : ''}
												</Grid.Column>
											))}
											</Grid>
										</Item.Description>
									</Item.Content>
								</Item>
							)
								})}
						</Item.Group>
					</Layout>
				)}
			/>
		);
	}