meez
meez

Reputation: 4788

Conditionally render an Astro component based on page type query

I am using Astro, GraphQL (Apollo Client), Typescript and React.

In my dynamic route: [...slug].astro file I need to conditionally render a certain Astro component.

I managed to that with:

 {data.page.type === 'PageOneType' && <PageOne />}
 {data.page.type === 'PageTwoType' && <PageTwo />}

Can I somehow make this more dynamic, so I don't have to add it static like above in case there are more page types in the feature?

Or do I need to pull in React for this?

Update: PageOne and PageTwo components will have different components and data. The data they get from a page query with different fragments:

import { gql } from '@apollo/client';

export default gql`
  query Page($target: String!) {
    page(target: $target) {
      type
      content {
        ... on PageOne {
          id
          title
        }
        ... on PageTwo {
          id
          description
        }
      }
    }
  }
`;

Upvotes: 1

Views: 1516

Answers (1)

Wil Moore III
Wil Moore III

Reputation: 7214

You can create a map with a string key and the component as the value.

const PageOne: React.FC = () => {
  return <div>Page One</div>;
};

const PageTwo: React.FC = () => {
  return <div>Page Two</div>;
};

const PageThree: React.FC = () => {
  return <div>Page Three</div>;
};

const PageMap: Record<string, React.FC> = {
  PageOneType: PageOne,
  PageTwoType: PageTwo,
  PageThreeType: PageThree
};

const Main: React.FC = () => {
  const Component = PageMap["PageOneType"];
  return <Component />;
};

Upvotes: 0

Related Questions