@material-ui/core/styles#ThemeProvider TypeScript Examples

The following examples show how to use @material-ui/core/styles#ThemeProvider. 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: HomepageTimer.test.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
it('changes default timezone to GMT', async () => {
  const configApi: ConfigApi = new ConfigReader({
    homepage: {
      clocks: [
        {
          label: 'New York',
          timezone: 'America/New_Pork',
        },
      ],
    },
    context: 'test',
  });

  const rendered = await renderWithEffects(
    <ThemeProvider theme={lightTheme}>
      <TestApiProvider apis={[[configApiRef, configApi]]}>
        <HomepageTimer />
      </TestApiProvider>
    </ThemeProvider>,
  );

  expect(rendered.getByText('GMT')).toBeInTheDocument();
});
Example #2
Source File: App.tsx    From ow-mod-manager with MIT License 6 votes vote down vote up
App = () => (
  <ErrorBoundary>
    <RecoilRoot>
      <ThemeProvider theme={theme}>
        <ErrorBoundary>
          <SettingsSubscription />
        </ErrorBoundary>
        <ErrorBoundary>
          <LocalModsSubscription />
        </ErrorBoundary>
        <ErrorBoundary>
          <RemoteModsSubscription />
        </ErrorBoundary>
        <ErrorBoundary>
          <LogsSubscription />
        </ErrorBoundary>
        <ErrorBoundary>
          <MainView />
        </ErrorBoundary>
      </ThemeProvider>
    </RecoilRoot>
  </ErrorBoundary>
)
Example #3
Source File: _app.tsx    From Figurify with Apache License 2.0 6 votes vote down vote up
function MyApp({Component, pageProps}) {
    return <>
        <Head>
            <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
            <title>{NAME}</title>
        </Head>
        <ThemeProvider theme={theme}>
            <Component {...pageProps} />
        </ThemeProvider>
    </>;
}
Example #4
Source File: _app.tsx    From Teyvat.moe with GNU General Public License v3.0 6 votes vote down vote up
_app: FunctionComponent<AppProps> = ({ Component, pageProps }) => {
  // TODO: Remove server-side JSS styles.
  // Normally you'd call 'useEffect' to call jssStyles.parentElement.removeChild(jssStyles);
  // However, I was experiencing an unknown bug where the old class names weren't being replaced
  // with the new ones, so I just got rid of the call so that the old class names would work.

  return (
    <>
      {/* StoreProvider allows hooks and components to access the Redux store. */}
      <StoreProvider store={store}>
        {/* ThemeProvider allows for child components to access the Material UI theme. */}
        <ThemeProvider theme={Theme}>
          {/* CSSBaseline injects a basic cascading style sheet for use by Material UI styling. */}
          <CssBaseline />
          {/* NotificationProvider handles the Notistack.
              Must be a child of StoreProvider since Redux handles notifications. */}
          <StylesProvider generateClassName={generateClassName}>
            <NotificationProvider>
              {/* ErrorHandler provides a fallback interface to use if the web page crashes. */}
              <ErrorHandler errorHandler={FullPageErrorHandler}>
                {/* Component provides the actual map content. */}
                <Component {...pageProps} />
              </ErrorHandler>
            </NotificationProvider>
          </StylesProvider>
        </ThemeProvider>
      </StoreProvider>
    </>
  );
}
Example #5
Source File: index.tsx    From prism-frontend with MIT License 6 votes vote down vote up
function App() {
  const isAuthenticated = useIsAuthenticated();

  const authRequired: boolean = get(appConfig, 'WFPAuthRequired', false);

  return (
    <ThemeProvider theme={muiTheme}>
      {/* Used to show notifications from redux as a snackbar. Notifications are stored in notificationState */}
      <Notifier />
      <Router>
        {isAuthenticated || !authRequired ? <Wrapper /> : <Login />}
      </Router>
    </ThemeProvider>
  );
}
Example #6
Source File: App.tsx    From BlinkWebUI with GNU General Public License v3.0 6 votes vote down vote up
render(): JSX.Element {
        return (
            <>
                <CssBaseline />
                <ThemeProvider theme={theme}>
                    <I18nextProvider i18n={i18n}>
                        <Router>
                            <MainLayout />
                        </Router>
                    </I18nextProvider>
                </ThemeProvider>
            </>
        );
    }
Example #7
Source File: index.tsx    From react-app-architecture with Apache License 2.0 6 votes vote down vote up
Routes = (): ReactElement => {
  // remove the css sent inline in the html on client side
  // useEffect in similar to componentDidMount for function components
  useEffect(() => {
    const jssStyles = document.querySelector('#jss-server-side');
    if (jssStyles && jssStyles.parentNode) jssStyles.parentNode.removeChild(jssStyles);
  }, []);

  return (
    <Provider store={store}>
      <CookiesProvider>
        <BrowserRouter>
          <ThemeProvider theme={theme}>
            <Route component={App} />
          </ThemeProvider>
        </BrowserRouter>
      </CookiesProvider>
    </Provider>
  );
}
Example #8
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
ABCWidgetCreator: WidgetCreator = (args) => {
  const el = document.createElement("span");
  ReactDOM.render(
    <ThemeProvider theme={selectedTheme.muiTheme}>
      <ABCWidget {...args}></ABCWidget>
    </ThemeProvider>,
    el
  );
  return el;
}
Example #9
Source File: test-utils.tsx    From dashboard with Apache License 2.0 6 votes vote down vote up
AllTheProviders: FC = ({ children }) => {
  return (
    <ThemeProvider theme={theme}>
      <Provider store={store}>{children}</Provider>
    </ThemeProvider>
  )
}
Example #10
Source File: themes.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
themes: AppTheme[] = [
  {
    id: 'light',
    title: 'Light Theme',
    variant: 'light',
    icon: <LightIcon />,
    Provider: ({ children }) => (
      <ThemeProvider theme={lightTheme}>
        <CssBaseline>{children}</CssBaseline>
      </ThemeProvider>
    ),
  },
  {
    id: 'dark',
    title: 'Dark Theme',
    variant: 'dark',
    icon: <DarkIcon />,
    Provider: ({ children }) => (
      <ThemeProvider theme={darkTheme}>
        <CssBaseline>{children}</CssBaseline>
      </ThemeProvider>
    ),
  },
]
Example #11
Source File: index.tsx    From twitch-live-extension with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
ReactDOM.render(
    <Provider store={store}>
        <ThemeProvider theme={darkTheme}>
            <Paper square>
                <Router>
                    <Switch>
                        <Route path="/settings" component={SettingsPage} />
                        <Route component={App} />
                    </Switch>
                </Router>
            </Paper>
        </ThemeProvider>
    </Provider>,
    document.getElementById('root'),
);
Example #12
Source File: Page.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
export function Page(props: Props) {
  const { themeId, children } = props;
  const { isMobile } = useSidebarPinState();
  const classes = useStyles({ isMobile });
  return (
    <ThemeProvider
      theme={(baseTheme: BackstageTheme) => ({
        ...baseTheme,
        page: baseTheme.getPageTheme({ themeId }),
      })}
    >
      <main className={classes.root}>{children}</main>
    </ThemeProvider>
  );
}
Example #13
Source File: App.tsx    From planning-poker with MIT License 6 votes vote down vote up
function App() {
  return (
    <div className="LightTheme">
    <ThemeProvider theme={theme} >
      <StylesProvider injectFirst>
        <CssBaseline />
        <Router>
          <Toolbar />
          <Switch>
            <Route path='/game/:id' component={GamePage} />
            <Route path='/join/:id' component={HomePage} />
            <Route exact path='/*' component={HomePage} />
          </Switch>
        </Router>
      </StylesProvider>
    </ThemeProvider>
    </div>
  );
}
Example #14
Source File: DefaultResultListItem.stories.tsx    From backstage with Apache License 2.0 6 votes vote down vote up
WithCustomHighlightedResults = () => {
  const customTheme = {
    ...lightTheme,
    overrides: {
      ...lightTheme.overrides,
      BackstageHighlightedSearchResultText: {
        highlight: {
          color: 'inherit',
          backgroundColor: 'inherit',
          fontWeight: 'bold',
          textDecoration: 'underline',
        },
      },
    },
  };

  return (
    <ThemeProvider theme={customTheme}>
      <CssBaseline>
        <DefaultResultListItem
          result={mockSearchResult}
          highlight={{
            preTag: '<tag>',
            postTag: '</tag>',
            fields: { text: 'some <tag>text</tag> from the search result' },
          }}
        />
      </CssBaseline>
    </ThemeProvider>
  );
}
Example #15
Source File: App.tsx    From gateway-ui with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
function App(): ReactElement {
  return (
    <ThemeProvider theme={theme}>
      <Provider>
        <>
          <CssBaseline />
          <Routes />
        </>
      </Provider>
    </ThemeProvider>
  )
}
Example #16
Source File: app.tsx    From webminidisc with GNU General Public License v2.0 6 votes vote down vote up
App = () => {
    const classes = useStyles();
    const { mainView, loading, darkMode, vintageMode } = useShallowEqualSelector(state => state.appState);

    if (vintageMode) {
        return <W95App></W95App>;
    }

    return (
        <React.Fragment>
            <ThemeProvider theme={darkMode ? darkTheme : lightTheme}>
                <CssBaseline />

                <main className={classes.layout}>
                    <Paper className={classes.paper}>
                        {mainView === 'WELCOME' ? <Welcome /> : null}
                        {mainView === 'MAIN' ? <Main /> : null}

                        <Box className={classes.controlsContainer}>{mainView === 'MAIN' ? <Controls /> : null}</Box>
                    </Paper>
                    <Typography variant="body2" color="textSecondary" className={classes.copyrightTypography}>
                        {'© '}
                        <Link rel="noopener noreferrer" color="inherit" target="_blank" href="https://stefano.brilli.me/">
                            Stefano Brilli
                        </Link>{' '}
                        {new Date().getFullYear()}
                        {'.'}
                    </Typography>
                </main>

                {loading ? (
                    <Backdrop className={classes.backdrop} open={loading}>
                        <CircularProgress color="inherit" />
                    </Backdrop>
                ) : null}
            </ThemeProvider>
        </React.Fragment>
    );
}
Example #17
Source File: App.tsx    From bee-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
App = ({ beeApiUrl, beeDebugApiUrl, lockedApiSettings }: Props): ReactElement => (
  <div className="App">
    <ThemeProvider theme={theme}>
      <SettingsProvider beeApiUrl={beeApiUrl} beeDebugApiUrl={beeDebugApiUrl} lockedApiSettings={lockedApiSettings}>
        <BeeProvider>
          <StampsProvider>
            <FileProvider>
              <FeedsProvider>
                <PlatformProvider>
                  <TopUpProvider>
                    <SnackbarProvider>
                      <Router>
                        <>
                          <CssBaseline />
                          <Dashboard>
                            <BaseRouter />
                          </Dashboard>
                        </>
                      </Router>
                    </SnackbarProvider>
                  </TopUpProvider>
                </PlatformProvider>
              </FeedsProvider>
            </FileProvider>
          </StampsProvider>
        </BeeProvider>
      </SettingsProvider>
    </ThemeProvider>
  </div>
)
Example #18
Source File: index.tsx    From logo-generator with MIT License 6 votes vote down vote up
// import { AuthProvider } from './context/AuthContext';

ReactDOM.render(
	<ThemeProvider theme={theme}>
		{/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
		<>
			<CssBaseline />
			<App />
		</>
	</ThemeProvider>
	,
	document.querySelector('#root'),
);
Example #19
Source File: index.tsx    From akashlytics with GNU General Public License v3.0 6 votes vote down vote up
ReactDOM.render(
  <React.StrictMode>
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <QueryClientProvider client={queryClient}>
        <IntlProvider locale={navigator.language}>
          <HelmetProvider>
            <SnackbarProvider maxSnack={3} dense hideIconVariant>
              <MediaQueryProvider>
                <Router>
                  <ScrollToTop />
                  <App />
                </Router>
              </MediaQueryProvider>
            </SnackbarProvider>
          </HelmetProvider>
        </IntlProvider>
      </QueryClientProvider>
    </ThemeProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
Example #20
Source File: index.tsx    From vscode-crossnote with GNU Affero General Public License v3.0 6 votes vote down vote up
AudioWidgetCreator: WidgetCreator = (args) => {
  const el = document.createElement("span");
  ReactDOM.render(
    <ThemeProvider theme={selectedTheme.muiTheme}>
      <AudioWidget {...args}></AudioWidget>
    </ThemeProvider>,
    el
  );
  return el;
}
Example #21
Source File: App.tsx    From Pi-Tool with GNU General Public License v3.0 6 votes vote down vote up
function App() {
    return (
        <div className="App" style={{ width: '100%', height: '100%' }}>
            <ThemeProvider theme={theme}>
                <CssBaseline />
                <Container maxWidth="md">
                    <OverclockingCard />
                    <MonitoringCard />
                    <ButtonMappingCard />
                    <CMLogo />
                </Container>
            </ThemeProvider>
        </div>
    );
}
Example #22
Source File: NotionFilter.tsx    From Nishan with MIT License 6 votes vote down vote up
function NotionFilter(props: Props) {
  const default_group_operator = props.default_group_operator ?? "and";
  const [filters, dispatch] = useReducer(notionFilterReducer, props.filters ?? {
    filters: [],
    operator: default_group_operator
  })

  return <NotionFilterContext.Provider value={{ filter_item_label: props.filter_item_label ?? false, default_group_operator, filters, dispatch, schema: props.schema, nestingLevel: props.nestingLevel ?? 5 }}>
    <ThemeProvider theme={theme}>
      <div className="NotionFilter" style={{ fontFamily: "Segoe UI" }}>
        <FilterGroup parent_filter={null} filter={filters} trails={[]} />
      </div>
    </ThemeProvider>
  </NotionFilterContext.Provider>
}
Example #23
Source File: App.tsx    From sphinx-win-linux-desktop with MIT License 6 votes vote down vote up
function Wrap(){
  const {ui} = useStores()
  return useObserver(()=>{
    if(ui.ready) return <ThemeProvider theme={ createMuiTheme({palette}) }><App /></ThemeProvider>
    return <Loading>
      <CircularProgress style={{color:'white'}} />
    </Loading>
  })
}
Example #24
Source File: radio_input.tsx    From jupyter-extensions with Apache License 2.0 6 votes vote down vote up
/** Funtional Component for Radio input fields */
export function RadioInput(props: RadioInputProps) {
  const { options, ...groupProps } = props;
  return (
    <ThemeProvider theme={theme}>
      <RadioGroup {...groupProps}>
        {options &&
          options.map((o, i) => (
            <FormControlLabel
              key={i}
              value={o.value}
              control={<Radio />}
              label={o.text}
              className={css.primaryTextColor}
            />
          ))}
      </RadioGroup>
    </ThemeProvider>
  );
}
Example #25
Source File: index.unit.spec.tsx    From next-typescript-materialui-jest-starter with MIT License 6 votes vote down vote up
describe("Button Unit Tests", () => {
  afterEach(() => {
    sandbox.verifyAndRestore();
    cleanup();
  });

  it("should render", () => {
    // Arrange
    sandbox.spy(React, "createElement");

    // Act
    const { container } = render(
      <ThemeProvider theme={theme}>
        <Button color="primary" name={word()} />
      </ThemeProvider>
    );

    // Assert
    expect(container.querySelector("button")).toBeInTheDocument();
    expect((React.createElement as SinonStub).calledWith(MuiButton)).toBe(true);
  });
});
Example #26
Source File: pageBuilder.tsx    From react-app-architecture with Apache License 2.0 5 votes vote down vote up
export default function pageBuilder(
  req: PublicRequest,
  pageinfo: PageInfo = {
    title: 'AfterAcademy | React Project',
    description: 'This is the sample project to learn and implement React app.',
  },
  currentState: Partial<RootState> = {},
): string {
  // create mui server style
  const sheets = new ServerStyleSheets();

  const authData = req.universalCookies.get(KEY_AUTH_DATA);
  if (authData?.tokens?.accessToken) {
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { tokens, ...data } = authData;
    currentState.authState = {
      data: data, // security
      isLoggingIn: false,
      isLoggingOut: false,
      isLoggedIn: true,
      isForcedLogout: false,
      isRedirectHome: false,
      message: null,
    };
  }

  const store = isDev
    ? configureStore(currentState)
    : createStore(rootReducer, currentState, applyMiddleware(thunk));

  // Render the component to a string
  const html = renderToString(
    sheets.collect(
      <Provider store={store}>
        <CookiesProvider cookies={req.universalCookies}>
          <StaticRouter location={req.url} context={{}}>
            <ThemeProvider theme={theme}>
              <App />
            </ThemeProvider>
          </StaticRouter>
        </CookiesProvider>
      </Provider>,
    ),
  );

  // Grab the CSS from our sheets.
  const css = sheets.toString();

  const baseUrl = `${getProtocol(req)}://${req.get('host')}`;
  const siteUrl = baseUrl + req.originalUrl;

  const { coverImg, title, description } = pageinfo;

  let htmlPage = render({
    html: html,
    css: css,
    preloadedState: store.getState(),
    siteUrl: siteUrl,
    title: title,
    coverImg: coverImg ? coverImg : `${baseUrl}/assets/og-cover-image.jpg`,
    description: description,
  });

  try {
    htmlPage = minifyHtml(htmlPage, {
      minifyCSS: true,
      minifyJS: true,
    });
  } catch (e) {
    console.log(e);
  }

  return htmlPage;
}
Example #27
Source File: MuiDecorator.tsx    From log4brains with Apache License 2.0 5 votes vote down vote up
export function MuiDecorator({ children }: Props) {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {children}
    </ThemeProvider>
  );
}
Example #28
Source File: index.tsx    From swap-ui with Apache License 2.0 5 votes vote down vote up
/**
 * A`Swap` component that can be embedded into applications. To use,
 * one can, minimally, provide a provider and token list to the component.
 * For example,
 *
 * ```javascript
 * <Swap provider={provider} tokenList={tokenList} />
 * ```
 *
 * All of the complexity of communicating with the Serum DEX and managing
 * its data is handled internally by the component.
 *
 * For information on other properties like earning referrals, see the
 * [[SwapProps]] documentation.
 */
export default function Swap(props: SwapProps): ReactElement {
  const {
    containerStyle,
    contentStyle,
    swapTokenContainerStyle,
    materialTheme,
    provider,
    tokenList,
    fromMint,
    toMint,
    fromAmount,
    toAmount,
    referral,
  } = props;

  // @ts-ignore
  const swapClient = new SwapClient(provider, tokenList);
  const theme = createMuiTheme(
    materialTheme || {
      palette: {
        primary: {
          main: "#2196F3",
          contrastText: "#FFFFFF",
        },
        secondary: {
          main: "#E0E0E0",
          light: "#595959",
        },
        error: {
          main: "#ff6b6b",
        },
      },
    }
  );
  return (
    <ThemeProvider theme={theme}>
      <TokenListContextProvider tokenList={tokenList}>
        <TokenContextProvider provider={provider}>
          <DexContextProvider swapClient={swapClient}>
            <SwapContextProvider
              fromMint={fromMint}
              toMint={toMint}
              fromAmount={fromAmount}
              toAmount={toAmount}
              referral={referral}
            >
              <SwapCard
                containerStyle={containerStyle}
                contentStyle={contentStyle}
                swapTokenContainerStyle={swapTokenContainerStyle}
              />
            </SwapContextProvider>
          </DexContextProvider>
        </TokenContextProvider>
      </TokenListContextProvider>
    </ThemeProvider>
  );
}
Example #29
Source File: App.tsx    From shadowsocks-electron with GNU General Public License v3.0 5 votes vote down vote up
App: React.FC = () => {
  const styles = useStyles();
  const darkMode = persistStore.get('darkMode') === 'true';
  const [theme] = useTheme(darkMode ? 'dark' : 'light');

  useEffect(() => {
    getConnectionStatus((status) => {
      store.dispatch({
        type: SET_STATUS,
        key: "connected",
        value: status
      });
    });

    MessageChannel.invoke('main', 'service:desktop', {
      action: 'setLocale',
      params: getFirstLanguage(persistStore.get('lang') as string)
    });
  }, []);

  return (
    <Provider store={store}>
      <PersistGate loading={<Loading />} persistor={persistor}>
        <ThemeProvider theme={theme}>
          <SnackbarProvider
            maxSnack={3}
            anchorOrigin={ {horizontal: 'center', vertical: 'top'} }
            autoHideDuration={2e3}
          >
            <HashRouter>
              <div className={styles.root}>
                <CssBaseline />
                <AppNav />
                <main className={styles.content}>
                  <div className={styles.toolbar} />
                  <RouterComp />
                </main>
              </div>
            </HashRouter>
          </SnackbarProvider>
        </ThemeProvider>
      </PersistGate>
    </Provider>
  );
}