next#NextComponentType TypeScript Examples

The following examples show how to use next#NextComponentType. 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: _app.tsx    From hypertext with GNU General Public License v3.0 6 votes vote down vote up
function FunctionalApp({ Component }: { Component: NextComponentType }): JSX.Element | null {
  const [painted, setPainted] = useState(false)
  useIsomorphicLayoutEffect(() => {
    setPainted(true)
  }, [])

  const { error, chainId } = useWeb3React()
  const queryParameters = useQueryParameters()
  const requiredChainId = queryParameters[QueryParameters.CHAIN]

  return !painted ? null : (
    <ColorModeProvider>
      <Favicon />
      <Provider>
        <Layout>
          {error ? (
            <Error />
          ) : typeof chainId !== 'number' ? (
            <Loading />
          ) : typeof requiredChainId === 'number' && chainId !== requiredChainId ? (
            <SwitchToChain requiredChainId={requiredChainId} />
          ) : (
            <Component />
          )}
        </Layout>
      </Provider>
    </ColorModeProvider>
  )
}
Example #2
Source File: _app.tsx    From resume-nextjs with MIT License 6 votes vote down vote up
export default function YosumeApp({
  Component,
  pageProps,
}: {
  Component: NextComponentType;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  pageProps: any;
}) {
  // eslint-disable-next-line react/jsx-props-no-spreading
  return <Component {...pageProps} />;
}
Example #3
Source File: _app.tsx    From storefront with MIT License 5 votes vote down vote up
App: NextComponentType<AppContext, AppInitialProps, Props> = ({
  apollo,
  apolloState,
  Component,
  pageProps,
  router,
}) => {
  useMount(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    jssStyles?.parentNode?.removeChild(jssStyles);

    ReactGA.initialize(process.env.GA_TRACKING_ID, {
      debug: process.env.NODE_ENV === 'development',
    });
    ReactGA.plugin.require('ec');
    ReactGA.pageview(router.asPath);

    router.events.on('routeChangeComplete', (url: string) => {
      ReactGA.pageview(url);
    });
  });

  return (
    <ApolloProvider client={apollo ?? createClient({ initialState: apolloState?.data })}>
      <SettingsProvider>
        <SettingsContext.Consumer>
          {({ settings, seo }) => (
            <>
              <Head>
                <meta
                  name="viewport"
                  content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
                />
                {seo.webmaster?.googleVerify != null && (
                  <meta name="google-site-verification" content={seo.webmaster.googleVerify} />
                )}
                {seo.webmaster?.msVerify != null && (
                  <meta name="msvalidate.01" content={seo.webmaster.msVerify} />
                )}
              </Head>
              <DefaultSeo
                title={settings.title ?? undefined}
                description={settings.description ?? undefined}
                canonical={absoluteURL(router.asPath)}
                openGraph={{
                  type: 'website',
                  locale: 'en_US',
                  url: absoluteURL(router.asPath),
                  site_name: settings.title ?? undefined,
                }}
                twitter={{
                  handle: '@artwithaliens',
                  cardType: 'summary_large_image',
                }}
              />
            </>
          )}
        </SettingsContext.Consumer>
        <ManagedUIContext>
          <CssBaseline />
          <Component {...pageProps} />
        </ManagedUIContext>
      </SettingsProvider>
    </ApolloProvider>
  );
}
Example #4
Source File: with-instantsearch.tsx    From next-instantsearch with MIT License 5 votes vote down vote up
withInstantSearch = (options: WithInstantSearchOptions) => (
  WrappedComponent: NextComponentType | any
) => {
  const onSearchStateChange =
    options.onSearchStateChange || utils.onSearchStateChange;

  const InstantSearchApp = (props: any) => {
    const [searchState, setSearchState] = useState(props.searchState);
    const router = useRouter();
    const indexName = props.indexName || options.indexName;

    const handleSearchStateChange = (state: any) => {
      setSearchState(state);
      onSearchStateChange(state, router);
    };

    return (
      <InstantSearch
        {...props}
        indexName={indexName}
        searchState={searchState}
        searchClient={options.searchClient}
        createURL={utils.createURL}
        onSearchStateChange={handleSearchStateChange}
      >
        <WrappedComponent {...props} />
      </InstantSearch>
    );
  };

  InstantSearchApp.getInitialProps = async (ctx: NextPageContext) => {
    const { asPath = "" } = ctx;

    const getInitialProps = WrappedComponent.getInitialProps || (() => ({}));
    const pageProps: any = await getInitialProps(ctx);

    const indexName = pageProps.indexName || options.indexName;

    const searchStateFromPath = utils.pathToSearchState(asPath);
    const searchStateFromProps = pageProps.searchState || {};
    const searchState = merge(searchStateFromPath, searchStateFromProps);

    const InstantSearchSSR = (props: any) => {
      const component = () => <InstantSearchApp {...pageProps} {...props} />;

      return options.decorate
        ? options.decorate({ ctx, component })
        : component();
    };

    const resultsState = await findResultsState(InstantSearchSSR, {
      indexName,
      searchClient: options.searchClient,
      searchState,
    });

    return {
      ...pageProps,
      indexName,
      searchState,
      resultsState,
    };
  };

  return hoistNonReactStatics(InstantSearchApp, WrappedComponent, {
    getInitialProps: true,
  });
}
Example #5
Source File: index.tsx    From nextjs-hasura-boilerplate with MIT License 4 votes vote down vote up
Navbar: NextComponentType = () => {
  const [session] = useSession();
  const { colorMode, toggleColorMode } = useColorMode();

  const handleToggleTheme = () => {
    toggleColorMode();
  };

  const linksForAllUsers = [
    {
      id: "home",
      label: "Home",
      href: "/",
    },
  ];

  const linksForAuthenticatedUsers = [
    {
      id: "feeds",
      label: "Feeds",
      href: "/feeds",
    },
    {
      id: "myAccount",
      label: "My Account",
      href: "/my-account",
    },
  ];

  const signInButtonNode = () => {
    if (session) {
      return false;
    }

    return (
      <Box>
        <Link href="/api/auth/signin">
          <Button
            onClick={(e) => {
              e.preventDefault();
              signIn();
            }}
          >
            Sign In
          </Button>
        </Link>
      </Box>
    );
  };

  const signOutButtonNode = () => {
    if (!session) {
      return false;
    }

    return (
      <Box>
        <Link href="/api/auth/signout">
          <Button
            onClick={(e) => {
              e.preventDefault();
              signOut();
            }}
          >
            Sign Out
          </Button>
        </Link>
      </Box>
    );
  };

  const themeToggleButtonNode = () => {
    return (
      <IconButton
        aria-label="Toggle theme"
        fontSize="20px"
        icon={colorMode === "dark" ? <SunIcon /> : <MoonIcon />}
        onClick={handleToggleTheme}
      />
    );
  };

  return (
    <Box>
      <Box p={4} shadow="lg" pos="relative">
        <Box maxW="xl" mx="auto" w="full">
          <Stack
            isInline
            spacing={4}
            align="center"
            justifyContent="space-between"
            w="full"
          >
            <Box>
              <Stack isInline spacing={4} align="center" fontWeight="semibold">
                {linksForAllUsers.map((link) => {
                  return (
                    <Box key={link.id}>
                      <Link href={link.href}>
                        <_Link>{link.label}</_Link>
                      </Link>
                    </Box>
                  );
                })}
                {session &&
                  linksForAuthenticatedUsers.map((link) => {
                    return (
                      <Box key={link.id}>
                        <Link href={link.href}>
                          <_Link>{link.label}</_Link>
                        </Link>
                      </Box>
                    );
                  })}
              </Stack>
            </Box>
            <Box>
              <Stack isInline spacing={4} align="center">
                {themeToggleButtonNode()}
                {signInButtonNode()}
                {signOutButtonNode()}
              </Stack>
            </Box>
          </Stack>
        </Box>
      </Box>
    </Box>
  );
}
Example #6
Source File: index.tsx    From nextjs-strapi-boilerplate with MIT License 4 votes vote down vote up
Navbar: NextComponentType = () => {
  const { data:session, status } = useSession();
  const { colorMode, toggleColorMode } = useColorMode();
  const bgColor = { light: "white", dark: "gray.800" };
  const color = { light: "gray.800", dark: "gray.100" };

  const handleToggleTheme = () => {
    console.log("hello");

    toggleColorMode();
  };

  const linksForAllUsers = [
    {
      id: "home",
      label: "Home",
      href: "/",
    },
  ];

  const linksForAuthenticatedUsers = [
    {
      id: "feeds",
      label: "Feeds",
      href: "/feeds",
    },
    {
      id: "myAccount",
      label: "My Account",
      href: "/my-account",
    },
  ];

  const signInButtonNode = () => {
    if (session) {
      return false;
    }

    return (
      <Box>
        <Link href="/api/auth/signin">
          <Button
            onClick={(e) => {
              e.preventDefault();
              signIn();
            }}
          >
            Sign In
          </Button>
        </Link>
      </Box>
    );
  };

  const signOutButtonNode = () => {
    if (!session) {
      return false;
    }

    return (
      <Box>
        <Link href="/api/auth/signout">
          <Button
            onClick={(e) => {
              e.preventDefault();
              signOut();
            }}
          >
            Sign Out
          </Button>
        </Link>
      </Box>
    );
  };

  const themeToggleButtonNode = () => {
    return (
      <IconButton
        aria-label="Toggle theme"
        fontSize="20px"
        icon={colorMode === "dark" ? "sun" : "moon"}
        onClick={handleToggleTheme}
      />
    );
  };

  return (
    <Box bg={bgColor[colorMode]}>
      <Box p={4} color={color[colorMode]} shadow="lg" pos="relative">
        <Box maxW="xl" mx="auto" w="full">
          <Stack
            isInline
            spacing={4}
            align="center"
            justifyContent="space-between"
            w="full"
          >
            <Box>
              <Stack isInline spacing={4} align="center" fontWeight="semibold">
                {linksForAllUsers.map((link) => {
                  return (
                    <Box key={link.id}>
                      <Link href={link.href}>
                        <_Link>{link.label}</_Link>
                      </Link>
                    </Box>
                  );
                })}
                {session &&
                  linksForAuthenticatedUsers.map((link) => {
                    return (
                      <Box key={link.id}>
                        <Link href={link.href}>
                          <_Link>{link.label}</_Link>
                        </Link>
                      </Box>
                    );
                  })}
              </Stack>
            </Box>
            <Box>
              <Stack isInline spacing={4} align="center">
                {themeToggleButtonNode()}
                {signInButtonNode()}
                {signOutButtonNode()}
              </Stack>
            </Box>
          </Stack>
        </Box>
      </Box>
    </Box>
  );
}
Example #7
Source File: with-instantsearch.spec.tsx    From next-instantsearch with MIT License 4 votes vote down vote up
describe("withInstantSearch", () => {
  const searchClient = algoliasearch("app_id", "api_key");
  const ctx = {
    asPath: "/?refinementList%5Bcategories%5D%5B0%5D=Appliances&page=1",
  } as NextPageContext;

  let Component: NextComponentType | any;
  let expectedSearchState: any;

  beforeEach(() => {
    jest.clearAllMocks();

    Component = () => null;
    Component.getInitialProps = jest.fn().mockResolvedValue({});

    expectedSearchState = {
      refinementList: {
        categories: ["Appliances"],
      },
      page: "1",
    };
  });

  it("should call Component.getInitialProps", async () => {
    const InstantSearchApp = withInstantSearch({ searchClient })(Component);
    await InstantSearchApp.getInitialProps(ctx);

    expect(Component.getInitialProps).toBeCalledWith(ctx);
  });

  it("should use indexName from options", async () => {
    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
    })(Component);

    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    expect(pageProps.indexName).toBe("foo");
  });

  it("should use indexName from component pageProps", async () => {
    Component.getInitialProps = jest.fn().mockResolvedValue({
      indexName: "bar",
    });

    const InstantSearchApp = withInstantSearch({ searchClient })(Component);

    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    expect(pageProps.indexName).toBe("bar");
  });

  it("should extract searchState from ctx.asPath", async () => {
    const InstantSearchApp = withInstantSearch({ searchClient })(Component);
    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    expect(pageProps.searchState).toEqual(expectedSearchState);
  });

  it("should merge searchState from component pageProps", async () => {
    expectedSearchState = {
      refinementList: {
        categories: ["Appliances", "TV & Home Theater"],
      },
      page: "1",
    };

    Component.getInitialProps = jest.fn().mockResolvedValue({
      searchState: {
        refinementList: {
          categories: ["TV & Home Theater"],
        },
      },
    });

    const InstantSearchApp = withInstantSearch({ searchClient })(Component);
    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    expect(pageProps.searchState).toEqual(expectedSearchState);
  });

  it("should call options.decorate", async () => {
    Component.getInitialProps = jest.fn().mockResolvedValue({
      foo: "bar",
    });

    const decorate = jest.fn();

    const InstantSearchApp = withInstantSearch({ searchClient, decorate })(
      Component
    );

    await InstantSearchApp.getInitialProps(ctx);

    expect(decorate).toHaveBeenCalledWith(
      expect.objectContaining({
        ctx,
        component: expect.any(Function),
      })
    );
  });

  it("should call findResultsState with InstantSearchApp", async () => {
    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
    })(Component);

    await InstantSearchApp.getInitialProps(ctx);

    const App = mockFindResultsState.mock.calls[0][0];
    // Check that props from findResultsState are passed down to InstantSearch
    const wrapper = mount(<App propFromSSR={true} />);

    expect(wrapper.find(InstantSearchApp).prop("propFromSSR")).toEqual(true);

    expect(mockFindResultsState.mock.calls[0][1]).toEqual({
      indexName: "foo",
      searchClient,
      searchState: expectedSearchState,
    });
  });

  it("should call findResultsState with decorated InstantSearchApp", async () => {
    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
      decorate: ({ component }) => <div id="Provider">{component()}</div>,
    })(Component);

    await InstantSearchApp.getInitialProps(ctx);

    const App = mockFindResultsState.mock.calls[0][0];
    const wrapper = mount(<App propFromSSR={true} />);

    expect(wrapper.exists("#Provider")).toEqual(true);
    // Check that props from findResultsState are passed down to InstantSearch
    expect(wrapper.find(InstantSearchApp).prop("propFromSSR")).toEqual(true);
  });

  it("should return expected pageProps", async () => {
    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
    })(Component);

    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    expect(pageProps).toEqual({
      indexName: "foo",
      resultsState: "some results",
      searchState: expectedSearchState,
    });
  });

  it("should hoist statics", () => {
    Component.foo = "bar";

    const InstantSearchApp = withInstantSearch({ searchClient })(Component);

    expect(InstantSearchApp.foo).toEqual(Component.foo);
  });

  it("should render InstantSearch with correct props", async () => {
    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
    })(Component);

    const pageProps = await InstantSearchApp.getInitialProps(ctx);

    // TODO: figure out how to mock resultsState
    const wrapper = mount(
      <InstantSearchApp {...pageProps} resultsState={null} />
    );
    const is = wrapper.find(InstantSearch);

    expect(is.prop("indexName")).toEqual("foo");
    expect(is.prop("searchState")).toEqual(expectedSearchState);
    expect(is.prop("resultsState")).toEqual(null);
    expect(is.prop("searchClient")).toEqual(searchClient);
    expect(is.prop("createURL")).toEqual(createURL);
    expect(is.prop("onSearchStateChange")).toEqual(expect.any(Function));
  });

  it("should should call default onSearchStateChange handler", () => {
    const utils = require("./utils");
    utils.onSearchStateChange = jest.fn();

    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
    })(Component);

    const wrapper = mount(<InstantSearchApp searchState={{}} />);

    const callback =
      wrapper.find(InstantSearch).prop("onSearchStateChange") || jest.fn();

    ReactTestUtils.act(() => {
      callback({
        foo: true,
      });
    });

    expect(utils.onSearchStateChange).toHaveBeenCalledWith(
      {
        foo: true,
      },
      "router instance"
    );
  });

  it("should should call options.onSearchStateChange handler", () => {
    const onSearchStateChange = jest.fn();

    const InstantSearchApp = withInstantSearch({
      indexName: "foo",
      searchClient,
      onSearchStateChange,
    })(Component);

    const wrapper = mount(<InstantSearchApp searchState={{}} />);

    const callback =
      wrapper.find(InstantSearch).prop("onSearchStateChange") || jest.fn();

    ReactTestUtils.act(() => {
      callback({
        foo: true,
      });
    });

    expect(onSearchStateChange).toHaveBeenCalledWith(
      {
        foo: true,
      },
      "router instance"
    );
  });
});