@emotion/react#CacheProvider TypeScript Examples

The following examples show how to use @emotion/react#CacheProvider. 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: emotion.ts    From vite-ssr with MIT License 6 votes vote down vote up
async function ssrCollector(context: Context) {
  // A subdependency of this dependency calls Buffer on import,
  // so it must be imported only in Node environment.
  // https://github.com/emotion-js/emotion/issues/2446
  // @ts-ignore
  let createEmotionServer: any = await import('@emotion/server/create-instance')
  createEmotionServer = createEmotionServer.default || createEmotionServer

  const cache = getCache()
  const { extractCriticalToChunks, constructStyleTagsFromChunks } =
    createEmotionServer(cache)

  return {
    collect(app: ReactElement) {
      return createElement(CacheProvider, { value: cache }, app)
    },
    toString(html: string) {
      const emotionChunks = extractCriticalToChunks(html)
      return constructStyleTagsFromChunks(emotionChunks)
    },
  }
}
Example #2
Source File: _app.tsx    From website with MIT License 6 votes vote down vote up
export default function CustomAppPage({ Component, pageProps, router }: AppProps) {
  const baseUrl = process.env.NEXT_PUBLIC_BASE_URL || ''

  return (
    <CacheProvider value={emotionCache}>
      <ChakraProvider theme={theme}>
        <Head>
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
          <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
          <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" />
          <link rel="shortcut icon" href="/favicon.ico" />
          <link rel="manifest" href="/manifest.json" />
          <meta name="msapplication-TileColor" content="#83e4fc" />
          <meta name="theme-color" content="#83e4fc" />
        </Head>

        <DefaultSeo
          title="ReactJS ID"
          titleTemplate="%s ยท ReactJS Indonesia"
          description="ReactJS ID adalah komunitas para developer React dan React Native. Kami mengadakan ajang meetup setiap bulannya, dimana para developer React bertukar informasi mengenai React dan ekosistemnya."
          canonical={baseUrl + router.asPath || ''}
          openGraph={{
            title: 'ReactJS ID',
            url: baseUrl,
            description:
              'ReactJS ID adalah komunitas para developer React dan React Native. Kami mengadakan ajang meetup setiap bulannya, dimana para developer React bertukar informasi mengenai React dan ekosistemnya.',
            type: 'website',
            site_name: 'ReactJS ID'
          }}
        />

        <Component {...pageProps} />
      </ChakraProvider>
    </CacheProvider>
  )
}
Example #3
Source File: _app.tsx    From next-page-tester with MIT License 6 votes vote down vote up
MyApp = ({ Component, pageProps }: AppProps) => (
  <>
    <CacheProvider value={cache}>
      <Global
        styles={css`
          body {
            color: red;
          }
        `}
      />
      <Component {...pageProps} />
    </CacheProvider>
  </>
)
Example #4
Source File: EditorOverlay.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
function Overlay(props: OverlayProps) {
  const { children, container } = props;

  const cache = React.useMemo(
    () =>
      createCache({
        key: `toolpad-editor-overlay`,
        prepend: true,
        container,
      }),
    [container],
  );

  return <CacheProvider value={cache}>{children}</CacheProvider>;
}
Example #5
Source File: index.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
function FrameContent(props: FrameContentProps) {
  const { children, document } = props;

  const cache = React.useMemo(
    () =>
      createCache({
        key: `code-component-sandbox`,
        prepend: true,
        container: document.head,
      }),
    [document],
  );

  return <CacheProvider value={cache}>{children}</CacheProvider>;
}
Example #6
Source File: _app.tsx    From mui-toolpad with MIT License 6 votes vote down vote up
export default function MyApp(props: MyAppProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>My page</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider theme={theme}>
          {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
          <CssBaseline />
          <Component {...pageProps} />
        </ThemeProvider>
      </QueryClientProvider>
    </CacheProvider>
  );
}
Example #7
Source File: emotion.ts    From vite-ssr with MIT License 6 votes vote down vote up
function clientProvider(context: Context) {
  const cache = getCache()

  return {
    provide(app: ReactElement) {
      return createElement(CacheProvider, { value: cache }, app)
    },
  }
}
Example #8
Source File: _app.tsx    From Cromwell with MIT License 6 votes vote down vote up
function App(props: AppPropsWithLayout) {
    const { Component, emotionCache = clientSideEmotionCache } = props;
    const getLayout = Component.getLayout ?? ((page) => page);
    const cmsProps: TPageCmsProps | undefined = props.pageProps?.cmsProps;
    const theme = getTheme(cmsProps?.palette);

    return (
        <CacheProvider value={emotionCache}>
            <ThemeProvider theme={theme}>
                {getLayout(<>
                    {Component && <Component {...(props.pageProps ?? {})} />}
                    {!isServer() && document?.body && ReactDOM.createPortal(
                        <div className={"global-toast"} ><ToastContainer /></div>, document.body)}
                </>)}
            </ThemeProvider>
        </CacheProvider>
    );
}
Example #9
Source File: _app.tsx    From react-hook-form-mui with MIT License 6 votes vote down vote up
export default function MyApp(props: MyAppProps) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props
  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>Demo for MUI react-hook-forms</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  )
}
Example #10
Source File: _document.tsx    From bouncecode-cms with GNU General Public License v3.0 6 votes vote down vote up
// ----------------------------------------------------------------------

MyDocument.getInitialProps = async ctx => {
  const originalRenderPage = ctx.renderPage;

  const cache = createEmotionCache();
  const {extractCriticalToChunks} = createEmotionServer(cache);

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: App => props => (
        <CacheProvider value={cache}>
          <App {...props} />
        </CacheProvider>
      ),
    });

  const initialProps = await Document.getInitialProps(ctx);

  const emotionStyles = extractCriticalToChunks(initialProps.html);
  const emotionStyleTags = emotionStyles.styles.map(style => (
    <style
      data-emotion={`${style.key} ${style.ids.join(' ')}`}
      key={style.key}
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML={{__html: style.css}}
    />
  ));

  return {
    ...initialProps,
    styles: [
      ...React.Children.toArray(initialProps.styles),
      ...emotionStyleTags,
    ],
  };
};
Example #11
Source File: StylesInjection.tsx    From symphony-ui-toolkit with Apache License 2.0 6 votes vote down vote up
StylesInjection = (props: Props) => {

  // @emotion/cache only accept alpha characters
  // Don't use shortid because it doesn't support less than 64 unique characters (See https://github.com/dylang/shortid#shortidcharactersstring)
  // Later we will use nanoid
  const uniqueAlphaCharacterId = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 10);

  const emotionCache = createCache({
    key: uniqueAlphaCharacterId,
    container: props.injectionPoint
  });

  return (
    <StyleSheetManager target={props.injectionPoint}>
      <CacheProvider value={emotionCache} >
        {props.children}
      </CacheProvider>
    </StyleSheetManager>
  )
}
Example #12
Source File: theme-provider.component.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
ThemeProviderComponent = (props) => {
  const { children } = props;

  return (
    <CacheProvider value={cache}>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        {children}
      </ThemeProvider>
    </CacheProvider>
  );
}
Example #13
Source File: _app.tsx    From Cromwell with MIT License 6 votes vote down vote up
function App(props: AppPropsWithLayout) {
  const pageContext = useAppPropsContext();
  const { Component, emotionCache = clientSideEmotionCache } = props;
  const getLayout = Component.getLayout ?? ((page) => page);
  const theme = getTheme(pageContext.pageProps?.cmsProps?.palette);

  React.useEffect(() => {
    if (!isServer()) {
      getRestApiClient()?.onError((info) => {
        if (info.statusCode === 429) {
          toast.error('Too many requests. Try again later');
        }
      }, '_app');
    }
  }, []);

  return (
    <CacheProvider value={emotionCache}>
      <ThemeProvider theme={theme}>
        {getLayout(<>
          {Component && <Component {...(props.pageProps ?? {})} />}
          {!isServer() && document?.body && ReactDOM.createPortal(
            <div className={"global-toast"} ><ToastContainer /></div>, document.body)}
        </>)}
      </ThemeProvider>
    </CacheProvider>
  );
}
Example #14
Source File: App.tsx    From tobira with Apache License 2.0 5 votes vote down vote up
SilenceEmotionWarnings: React.FC<{ children: ReactNode }> = ({ children }) => {
    const cache = createEmotionCache({ key: "css" });
    cache.compat = true;

    return <CacheProvider value={cache}>{children}</CacheProvider>;
}
Example #15
Source File: preview.tsx    From react-hook-form-mui with MIT License 5 votes vote down vote up
decorators = [(Story: Story) => (
  <CacheProvider value={clientSideEmotionCache}>
    <ThemeProvider theme={theme}>
      <Suspense fallback={<div>loading</div>}><Story /></Suspense>
    </ThemeProvider>
  </CacheProvider>
)]
Example #16
Source File: _app.tsx    From tams-club-cal with MIT License 5 votes vote down vote up
export default function MyApp(props: MyAppProps) {
    const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;
    const [dark, setDark] = useState(false);

    // Set the dark theme on load
    // Both the dark state variable and setDark state function will
    // be passed into the component props
    useEffect(() => {
        // Get the previously saved dark theme choice from cookies
        const cookies = new Cookies();
        const prevDark = cookies.get('dark');

        if (!prevDark) {
            // If it does not exist, use the system dark theme
            const systemDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
            setDark(systemDark);
            cookies.set('dark', systemDark, { sameSite: 'strict', path: '/' });
        } else {
            // Otherwise, use the previously set setting
            setDark(prevDark === 'true');
        }
    }, []);

    useEffect(() => {
        const cookies = new Cookies();
        cookies.set('dark', dark, { sameSite: 'strict', path: '/' });
    }, [dark]);

    return (
        <CacheProvider value={emotionCache}>
            <Head>
                <meta name="viewport" content="initial-scale=1, width=device-width" />
                <title>TAMS Club Calendar</title>
                <meta
                    key="description"
                    name="description"
                    content="The TAMS Club Calendar is a fully contained event tracker, club/volunteering database, and general resource center. This is the unofficial club event calendar for the Texas Academy of Mathematics and Science!"
                />
                <meta key="title" property="og:title" content="TAMS Club Calendar" />
                <meta key="type" property="og:type" content="website" />
                <meta key="url" property="og:url" content="https://tams.club/" />
                <meta key="image-0" property="og:image" content="https://cdn.tams.club/social-cover.webp" />
                <meta key="image-1" property="og:image:width" content="1200" />
                <meta key="image-2" property="og:image:height" content="630" />
                <meta key="site-name" property="og:site_name" content="TAMS Club Calendar" />
                <meta key="card" name="twitter:card" content="summary" />
                <meta key="title-1" name="twitter:title" content="TAMS Club Calendar" />
                <meta
                    key="description-1"
                    name="twitter:description"
                    content="The TAMS Club Calendar is a fully contained event tracker, club/volunteering database, and general resource center. This is the unofficial club event calendar for the Texas Academy of Mathematics and Science!"
                />
                <meta key="image-3" name="twitter:image" content="https://cdn.tams.club/social-cover.webp" />

                <meta key="theme-color" name="theme-color" content={theme.palette.primary.main} />
            </Head>
            <StyledEngineProvider injectFirst>
                <ThemeProvider theme={dark ? darkTheme : theme}>
                    <LocalizationProvider dateAdapter={AdapterDayjs}>
                        <CssBaseline />
                        <Menu dark={dark} setDark={setDark} />
                        <Component {...pageProps} />
                    </LocalizationProvider>
                </ThemeProvider>
            </StyledEngineProvider>
        </CacheProvider>
    );
}
Example #17
Source File: index.tsx    From NekoMaid with MIT License 5 votes vote down vote up
ReactDom.render(<CacheProvider value={createCache({ key: 'nm', stylisPlugins: [] })}>
  {url ? <HashRouter><App /></HashRouter> : <ServerSwitch open />}
</CacheProvider>, document.getElementById('app'))
Example #18
Source File: _app.tsx    From frontend with MIT License 4 votes vote down vote up
function CustomApp({
  Component,
  emotionCache = clientSideEmotionCache,
  pageProps: { session, dehydratedState, ...pageProps },
}: CustomAppProps) {
  const router = useRouter()
  const { i18n } = useTranslation()
  const { initialize, trackEvent } = useGTM()
  const onError = useCallback((error: unknown) => {
    if (error && isAxiosError(error)) {
      // Redirect to login
      if (error.response?.status === 401) {
        router.push({
          pathname: routes.login,
          query: { callbackUrl: router.asPath },
        })
      }
    }
  }, [])

  const [queryClient] = React.useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            queryFn,
            onError,
            staleTime: 25000,
          },
          mutations: { onError },
        },
      }),
  )

  useEffect(() => {
    // Init GTM
    initialize({
      events: { user_lang: i18n.language },
    })
  }, [])

  // Register route change complete event handlers
  useEffect(() => {
    const onRouteChange = (url: string) => {
      trackEvent({
        event: 'page_view',
        user_lang: i18n.language,
        page_title: document.title,
        page_pathname: url,
        page_location:
          document.location.protocol +
          '//' +
          document.location.hostname +
          document.location.pathname +
          document.location.search,
      })
    }

    router.events.on('routeChangeComplete', onRouteChange)
    return () => router.events.off('routeChangeComplete', onRouteChange)
  }, [i18n.language])

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>Podkrepi.bg</title>
        <meta name="viewport" content="minimum-scale=1, initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <SessionProvider session={session} refetchInterval={60}>
          <QueryClientProvider client={queryClient}>
            <Hydrate state={dehydratedState}>
              <Component {...pageProps} />
            </Hydrate>
          </QueryClientProvider>
        </SessionProvider>
      </ThemeProvider>
    </CacheProvider>
  )
}