### Example of dynamic documentation querying Source: https://docs.tss-react.dev/publish-a-module-that-uses-tss Demonstrates how to query documentation dynamically by appending an 'ask' parameter to the GET request URL. This is useful for retrieving specific information or clarifications. ```http GET https://docs.tss-react.dev/publish-a-module-that-uses-tss.md?ask= ``` -------------------------------- ### Install tss-react Source: https://docs.tss-react.dev/ Install tss-react and its peer dependency @emotion/react using yarn. ```bash yarn add tss-react @emotion/react ``` -------------------------------- ### Query documentation dynamically Source: https://docs.tss-react.dev/detecting-unused-classes Perform an HTTP GET request to the documentation URL with an 'ask' query parameter to get specific information. ```http GET https://docs.tss-react.dev/detecting-unused-classes.md?ask= ``` -------------------------------- ### User installation command for a module using MUI Source: https://docs.tss-react.dev/publish-a-module-that-uses-tss Instruct your users to install your module along with the required MUI and emotion packages. Ensure the MUI version meets the specified requirement. ```bash yarn add YOUR_MODULE @mui/material @emotion/react @emotion/styled ``` -------------------------------- ### Install TSS-React and MUI Dependencies Source: https://docs.tss-react.dev/ Install the necessary packages for TSS-React and Material-UI. This is a prerequisite for using TSS-React with MUI. ```bash yarn add @mui/material @emotion/styled @emotion/react #Required for MUI yarn add tss-react ``` -------------------------------- ### User installation command for a module not using MUI Source: https://docs.tss-react.dev/publish-a-module-that-uses-tss Instruct your users to install your module along with the required emotion package. This command is for users whose projects do not depend on MUI. ```bash yarn add YOUR_MODULE @emotion/react ``` -------------------------------- ### Add Emotion Server Package Source: https://docs.tss-react.dev/ssr/other-backends Install the Emotion server package to enable SSR capabilities. ```bash yarn add @emotion/server ``` -------------------------------- ### Querying Documentation Dynamically Source: https://docs.tss-react.dev/mui-global-styleoverrides Perform an HTTP GET request on the current page URL with the `ask` query parameter to get dynamic information. The question should be specific and in natural language. ```http GET https://docs.tss-react.dev/mui-global-styleoverrides.md?ask= ``` -------------------------------- ### Query API Documentation Source: https://docs.tss-react.dev/api To get more information not directly on the page, query the documentation dynamically. Perform a GET request with the 'ask' query parameter containing your question. ```http GET https://docs.tss-react.dev/api.md?ask= ``` -------------------------------- ### Querying Documentation with `ask` Parameter Source: https://docs.tss-react.dev/ssr/gatsby To get additional information not directly on this page, perform an HTTP GET request with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.tss-react.dev/ssr/gatsby.md?ask= ``` -------------------------------- ### Query Documentation Dynamically Source: https://docs.tss-react.dev/troubleshoot-migration-to-muiv5-with-tss To get additional information not explicitly on this page, perform an HTTP GET request to the current page URL with the `ask` query parameter. The question should be specific and self-contained. ```http GET https://docs.tss-react.dev/troubleshoot-migration-to-muiv5-with-tss.md?ask= ``` -------------------------------- ### Perform HTTP GET Request with `ask` Parameter Source: https://docs.tss-react.dev/api/withstyles Use this method to query documentation dynamically when information is not explicitly present. The question should be specific and self-contained. ```http GET https://docs.tss-react.dev/api/withstyles.md?ask= ``` -------------------------------- ### Update SSR Setup for MUI with tss-react Source: https://docs.tss-react.dev/update-to-v4 Replaces the old MUI cache setup with the new `createEmotionSsrAdvancedApproach` from `tss-react/nextJs` for improved SSR handling. Ensure you import `withEmotionCache` from the correct location. ```diff // src/pages/_app.tsx -import type { EmotionCache } from "@emotion/cache"; -import createCache from "@emotion/cache"; -import { CacheProvider } from '@emotion/react'; +import { createEmotionSsrAdvancedApproach } from "tss-react/nextJs"; -let muiCache: EmotionCache | undefined = undefined; -export const createMuiCache = () => muiCache = createCache({ "key": "mui", "prepend": true }); +const { EmotionCacheProvider, withEmotionCache } = createEmotionSsrAdvancedApproach({ "key": "css" }); +export { withEmotionCache }; function App({ Component, pageProps }: AppProps) { ... - + - + ); ``` ```diff // src/pages/_document.tsx import BaseDocument from "next/document"; -import { withEmotionCache } from "tss-react/nextJs"; -import { createMuiCache } from "./_app"; +import { withEmotionCache } from "./_app"; -export default withEmotionCache({ - "Document": BaseDocument, - "getCaches": () => [createMuiCache()] -}); +export default withEmotionCache(BaseDocument); ``` -------------------------------- ### Vite React TS Project Setup Source: https://docs.tss-react.dev/ Configuration for a Vite project using React and TypeScript, including necessary dependencies and build settings. ```json { "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } ``` -------------------------------- ### Applying Styles with withStyles Source: https://docs.tss-react.dev/api/withstyles This example demonstrates how to use withStyles to apply styles to a React component. Styles can be defined using a function that receives theme and props. Media queries can be used for responsive design. ```javascript import React from 'react'; import { withStyles } from '@material-ui/core/styles'; import { Theme } from '@material-ui/core/styles'; interface Props { colorSmall?: string; } interface Classes { root: string; text: string; span: string; } interface MyComponentProps { classes: Classes; } class MyComponent extends React.Component { render() { const { classes } = this.props; return (
The background color should be different when the screen is small.
); } } const styles = (theme: Theme, props: Props) => ({ root: { backgroundColor: theme.palette.primary.main, height: 100 }, text: { border: "1px solid red" }, "@media (max-width: 960px)": { root: { backgroundColor: props.colorSmall } } }); const MyComponentStyled = withStyles(MyComponent, styles); export default MyComponentStyled; ``` -------------------------------- ### Example React Component with tss-react Source: https://docs.tss-react.dev/ This React component demonstrates the usage of tss-react for styling. It includes responsive styles based on screen size and hover effects. ```typescript import React, { useState } from 'react'; import { makeStyles } from 'tss-react'; interface MyButtonProps { color: 'red' | 'blue'; } export const MyButton: React.FC = ({ color }) => { const [isClicked, setIsClicked] = useState(false); const useStyles = makeStyles<{ color: 'red' | 'blue' }>()( (theme, { color }) => ({ root: { color, '&:hover': { border: '4px solid black', }, [theme.breakpoints.up('md')]: { border: '10px solid cyan', }, }, }) ); const { classes } = useStyles({ color }); return ( ); }; ``` -------------------------------- ### Configure Emotion Caches for MUI and tss-react Source: https://docs.tss-react.dev/troubleshoot-migration-to-muiv5-with-tss Use this setup for Create React App, Vite, and other SPA frameworks to ensure tss-react styles take precedence over MUI styles by using separate Emotion caches. Ensure MUI styles are injected first by setting `prepend: true` for the MUI cache. ```tsx import React from "react"; import ReactDOM from "react-dom/client"; import { CacheProvider } from "@emotion/react"; import { TssCacheProvider } from "tss-react"; import createCache from "@emotion/cache"; import App from "./App"; const muiCache = createCache({ key: "mui", prepend: true }); const tssCache = createCache({ key: "tss" }); ReactDOM.createRoot(document.getElementById("root")!).render( //NOTE: Don't use ); ``` -------------------------------- ### Package.json for a module using MUI Source: https://docs.tss-react.dev/publish-a-module-that-uses-tss Configure your module's package.json to include tss-react and peer dependencies for React and MUI. Users will install your module along with these peer dependencies. ```json "name": "YOUR_MODULE", "dependencies": { "tss-react": "^4.0.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.2 || 18.0.0" , "@mui/material": "^5.9.3 || ^6.0.0", "@emotion/react": "^11.4.1" }, "devDependencies": { "@mui/material": "^5.0.1", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.8.1" } ``` -------------------------------- ### Add eslint-plugin-tss-unused-classes dependency Source: https://docs.tss-react.dev/detecting-unused-classes Install the ESLint plugin as a development dependency using yarn. ```bash yarn add --dev eslint-plugin-tss-unused-classes ``` -------------------------------- ### App Component with Emotion Cache Source: https://docs.tss-react.dev/ssr/other-backends Defines the main App component and a function to create a cache instance for Emotion. This setup ensures that styles are correctly managed and applied during SSR. ```tsx import { CacheProvider } from "@emotion/react"; import createCache, { type EmotionCache } from "@emotion/cache"; let appCache: EmotionCache | undefined = undefined; export const crateAppCache = () => appCache = createCache({ "key": "css" }); export function App(){ return ( {/* ... */} ); } ``` -------------------------------- ### Create a Button Component with tss-react Styling Source: https://docs.tss-react.dev/ This example demonstrates how to create a custom button component using `tss-react` for styling. It utilizes `makeStyles` to define styles based on component state and integrates with Material-UI's `Button` component. The `cx` utility from `tss-react` is used for class name management, prioritizing provided class names over root styles. ```typescript import { makeStyles, withStyles } from "tss-react/mui"; // "tss-react/mui-compat" if your project is using Typescript < 4.4 import Button from "@mui/material/Button"; import { useState } from "react"; type Props = { className?: string; }; export function MyButton(props: Props) { const { className } = props; const [isClicked, setIsClicked] = useState(false); const { classes, cx } = useStyles({ color: isClicked ? "blue": "red" }); //Thanks to cx, className will take priority over classes.root //With TSS you must stop using clsx and use cx instead. //More info here: https://github.com/mui/material-ui/pull/31802#issuecomment-1093478971 return ( ); } const useStyles = makeStyles<{ color: "red" | "blue" }>()( (theme, { color }) => ({ root: { // The color of the text is either blue or red depending of // the state fo the component. color, // When the curser is over the button has a black border "&:hover": { border: '4px solid black' }, // On screens bigger than MD the button will have a big cyan border [theme.breakpoints.up("md")]: { border: '10px solid cyan' } } }) ); ``` -------------------------------- ### App Component Setup for Separate Caches Source: https://docs.tss-react.dev/ssr/other-backends This component sets up the necessary cache providers for both MUI and TSS. It ensures that a new cache is created if one doesn't already exist, allowing for distinct caching strategies for each library. ```tsx import { CacheProvider } from "@emotion/react"; import createCache, { type EmotionCache } from "@emotion/cache"; import { TssCacheProvider } from "tss-react"; let muiCache: EmotionCache | undefined = undefined; export const createMuiCache = () muiCache = createCache({ "key": "mui", "prepend": true }); let tssCache: EmotionCache | undefined = undefined; export const createTssCache = () muiCache = createCache({ "key": "tss" }); export function App(){ return ( {/* ... */} ); } ``` -------------------------------- ### Package.json for a module not using MUI Source: https://docs.tss-react.dev/publish-a-module-that-uses-tss Configure your module's package.json to include tss-react and peer dependencies for React and emotion. Users will install your module along with these peer dependencies. ```json "name": "YOUR_MODULE", "dependencies": { "tss-react": "^4.0.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.2 || ^18.0.0", "@emotion/react": "^11.4.1" }, "devDependencies": { "@emotion/react": "^11.4.1" } ``` -------------------------------- ### TSS React makeStyles API with Params and Nested Selectors Source: https://docs.tss-react.dev/nested-selectors This example demonstrates using parameters and nested selectors with tss-react's makeStyles API. It styles child elements based on theme colors and applies conditional styling. ```tsx export function App() { const { classes, cx } = useStyles({ "color": "primary" }); return (
The Background takes the primary theme color when the mouse is hovering over the parent.
The Background takes the primary theme color when the mouse is hovering over the parent. I am smaller than the other child.
); } const useStyles = makeStyles< { color: "primary" | "secondary" }, "child" | "small" >({ uniqId: "GnWmDK" })((theme, { color }, classes) => ({ "root": { "padding": 30, [`&:hover .${classes.child}`]: { "backgroundColor": theme.palette[color].main } }, "small": {}, "child": { "border": "1px solid black", "height": 50, [`&.${classes.small}`]: { "height": 30 } } })); ``` -------------------------------- ### TSS React Modern API with Params and Nested Selectors Source: https://docs.tss-react.dev/nested-selectors This example demonstrates using parameters and nested selectors with tss-react's modern API. It styles a child element based on a theme color and applies different styles to a smaller child. ```tsx export function MyComponent() { const { classes, cx } = useStyles({ color: "primary" }); return (
The Background takes the primary theme color when the mouse is hovering over the parent.
The Background takes the primary theme color when the mouse is hovering over the parent. I am smaller than the other child.
); } const useStyles = tss .withName("MyComponent") .withNestedSelectors<"child" | "small">() .withParams<{ color: "primary" | "secondary" }>() .create(({ theme, color, classes })=> ({ root: { padding: 30, [`&:hover .${classes.child}`]: { backgroundColor: theme.palette[color].main } }, small: {}, child: { border: "1px solid black", height: 50, [`&.${classes.small}`]: { height: 30 } } })); ``` -------------------------------- ### TSS React makeStyles API Nested Selectors Source: https://docs.tss-react.dev/nested-selectors This example shows how to implement nested selectors using the makeStyles API in tss-react. It styles a child element when the parent is hovered. ```tsx export function App() { const { classes } = useStyles(); return (
Background turns red when the mouse is hovering over the parent.
); } const useStyles = makeStyles({ uniqId: "QnWmDL" // In SSR setups, you must give an unique id to all // your useStyles that uses nested selectors. // See below for mor infos. })( (_theme, _params, classes) => ({ "parent": { "padding": 30, [`&:hover .${classes.child}`]: { "backgroundColor": "red" } }, "child": { "backgroundColor": "blue" }, }) ); ``` -------------------------------- ### Render the Button Component in the Application Source: https://docs.tss-react.dev/ This snippet shows how to render the `MyButton` component within the main application structure. It uses `tss-react`'s `useStyles` hook to apply global styles or themes if needed, although in this specific example, it's primarily used to demonstrate the hook's presence. ```typescript import * as React from 'react'; import * as ReactDOM from 'react-dom/client'; import { useStyles } from 'tss-react/mui'; import { MyButton } from './MyButton'; ReactDOM.createRoot(document.getElementById('root')!).render( ); function Root() { const { css } = useStyles(); return ( ); } ``` -------------------------------- ### Basic useStyles Hook Usage Source: https://docs.tss-react.dev/api/tss-usestyles Use the useStyles hook to get css and cx functions for inline styling. The css function is similar to @emotion/css, and cx is similar to clsx but with class priority. ```tsx import { useStyles } from "tss-react" // or "tss-react/mui"; function MyComponent(){ const { css, //<- Like the css function of @emotion/css cx //<- Like the cx function of @emotion/css, also known as clsx. It's smarter though, classes that comes last take priority. } = useStyles(); return (
Hello World
); } ``` -------------------------------- ### Using MUI sx syntax with tss-react (makeStyles) Source: https://docs.tss-react.dev/mui-sx-syntax Illustrates how to use MUI's sx syntax with the makeStyles API in tss-react. This approach also allows for direct integration of styles within JSX. ```tsx import { unstable_styleFunctionSx } from "@mui/system"; import type { CSSObject } from "tss-react"; export const styleFunctionSx = unstable_styleFunctionSx as (params: object) => CSSObject; function TestSxComponent() { const { classes } = useStyles(); return (
Should look like: https://mui.com/material-ui/react-box/#the-sx-prop but in green.
); }; const useStyles = makeStyles()(theme => ({ root: styleFunctionSx({ theme, sx: { width: 300, height: 300, backgroundColor: "primary.dark", "&:hover": { backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7] } } }) })); ``` -------------------------------- ### Enable plugin in eslint.config.js Source: https://docs.tss-react.dev/detecting-unused-classes Configure ESLint to use the tss-unused-classes plugin and enable the unused-classes rule. This configuration is for projects where ESLint is installed manually. ```javascript import tssUnusedClasses from 'eslint-plugin-tss-unused-classes' export default tseslint.config( { ignores: ['dist'] }, { plugins: { // ... 'tss-unused-classes': tssUnusedClasses, }, rules: { // ... 'tss-unused-classes/unused-classes': 'warn', }, }, ) ``` -------------------------------- ### Create tss instance with custom theme Source: https://docs.tss-react.dev/ Set up a tss instance with a custom theme context. The useContext function defines the theme object that will be available to your styles. ```typescript import { createTss } from "tss-react"; function useContext() { const myTheme = { primaryColor: "#32CD32", // This is LimeGreen in hex }; // You can return anything here, you decide what's the context. return { myTheme }; } export const { tss } = createTss({ useContext }); export const useStyles = tss.create({}); ``` -------------------------------- ### Simplified import with tsconfig paths Source: https://docs.tss-react.dev/ After configuring tsconfig.json and vite-tsconfig-paths, imports can be simplified. ```typescript import { tss } from "tss"; ``` -------------------------------- ### MyComponent with makeStyles API Source: https://docs.tss-react.dev/mui-global-styleoverrides Defines a component using the older makeStyles API, showing how to pass props and ownerState for dynamic styling. ```tsx export type Props = { className?: string; classes?: Partial["classes"]>; lightBulbBorderColor: string; } function MyComponent(props: Props) { const { className } = props; const [isOn, toggleIsOn] = useReducer(isOn => !isOn, false); const { classes, cx } = useStyles(undefined, { props, "ownerState": { isOn } }); return (

Div should have a border, background should be white

Light bulb should have black border, it should be yellow when turned on.

); } const useStyles = makeStyles({ name: "MyComponent" })({ "root": { "border": "1px solid black", "width": 500, "height": 200, "position": "relative", "color": "black" }, "lightBulb": { "position": "absolute", "width": 50, "height": 50, "top": 120, "left": 500/2 - 50, "borderRadius": "50%" } }); ``` -------------------------------- ### Configure Vite for React Project Source: https://docs.tss-react.dev/ This is the default Vite configuration file for a React project. It sets up the necessary plugins for React development. ```typescript import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()] }) ``` -------------------------------- ### TSS React Modern API Nested Selectors Source: https://docs.tss-react.dev/nested-selectors Achieve nested selector functionality with tss-react's modern API. This example shows how to style a child element when the parent is hovered over. ```tsx export function MyComponent() { const { classes } = useStyles(); return (
Background turns red when the mouse is hovering over the parent.
); } const useStyles = tss .withName("MyComponent") // It's important to set a name in SSR setups .withNestedSelectors<"child">() .create(({ classes }) => ({ parent: { padding: 30, [`&:hover .${classes.child}`]: { backgroundColor: "red" } }, child: { backgroundColor: "blue" }, })); ``` -------------------------------- ### Import Exposed APIs from tss-react Source: https://docs.tss-react.dev/api Import the core APIs for styling in tss-react. Use `createTss` for dynamic themes and `tss` when a dynamic theme is not needed. `keyframes` and `GlobalStyles` are also available for advanced styling. ```typescript import { createTss, //<- (From 4.9) The Modern API, you provide your context like a dynamic theme for example. tss, //<- The Modern API, to use when you don't have a dynamic theme object that you want to make available when you write your styles. keyframes, //<- The function as defined in @emotion/react and @emotion/css GlobalStyles, //<- A component to define global styles. } from "tss-react"; ``` ```typescript import { tss // <- (From 4.9) The Modern API, that use the global MUI theme as context. It's also configured to enable global theme overrides on your custom components. makeStyles, //<- A function similar to @material-ui/core/styles configured to use the global MUI theme. withStyles, //<- A function similar to @material-ui/core/styles configured to use the global MUI theme. } from "tss-react/mui"; ``` -------------------------------- ### Using useStyles Hook for cx, css, and theme Source: https://docs.tss-react.dev/api/makestyles Import and use the useStyles hook directly from createMakeAndWithStyles when you need access to cx, css, or theme without defining custom classes. ```typescript import { createMakeAndWithStyles } from "tss-react"; function useTheme() { return { "primaryColor": "#32CD32", }; } export const { makeStyles, useStyles //<- This useStyles is like the useStyles you get when you // call makeStyles but it doesn't return a classes object. } = createMakeAndWithStyles({ useTheme }); ``` -------------------------------- ### Using MUI sx syntax with tss-react (Modern API) Source: https://docs.tss-react.dev/mui-sx-syntax Demonstrates the modern API approach for applying MUI's sx syntax within tss-react. This method is useful for intertwining JSX and styles directly. ```tsx import { mui } from "tss-react/mui"; import { unstable_styleFunctionSx } from "@mui/system"; import type { CSSObject } from "tss-react"; export const styleFunctionSx = unstable_styleFunctionSx as (params: object) => CSSObject; function TestSxComponent() { const { classes } = useStyles(); return (
Should look like: https://mui.com/material-ui/react-box/#the-sx-prop but in green.
); }; const useStyles = tss .create({ root: styleFunctionSx({ theme, sx: { width: 300, height: 300, backgroundColor: "primary.dark", "&:hover": { backgroundColor: 'primary.main', opacity: [0.9, 0.8, 0.7] } } }) }); ``` -------------------------------- ### Configure tsconfig.json for Vite Source: https://docs.tss-react.dev/ Configure tsconfig.json with 'baseUrl': 'src' and use the vite-tsconfig-paths plugin to simplify import paths in Vite projects. ```json { "compilerOptions": { "baseUrl": "src" } } ``` -------------------------------- ### Using Emotion's CacheProvider Source: https://docs.tss-react.dev/cache Wrap your application with Emotion's `CacheProvider` to make a custom cache available contextually. This cache will be used by tss-react and any other Emotion-aware libraries. ```tsx import { CacheProvider } from "@emotion/react"; import createCache from "@emotion/cache"; const cache = createCache({ "key": "custom" }); render( {/* ... */} ); ``` -------------------------------- ### useStyles Hook Source: https://docs.tss-react.dev/api/makestyles The useStyles hook returns classes, cx, css, and theme. ```APIDOC ## useStyles() Hook ### Description Beside the `classes`, `useStyles` also returns `cx`, `css` and your `theme`. `css` is the function as defined in [@emotion/css](https://emotion.sh) `cx` is the function as defined in [@emotion/css](https://emotion.sh/docs/@emotion/css#cx) ### Usage ```typescript const { classes, cx, css, theme } = useStyles(/*...*/); ``` ### Standalone useStyles Hook In some components you may need `cx`, `css` or `theme` without defining custom `classes`. For that purpose you can use the `useStyles` hook returned by `createMakeStyles`. `makeStyles.ts` ```typescript import { createMakeAndWithStyles } from "tss-react"; function useTheme() { return { "primaryColor": "#32CD32", }; } export const { makeStyles, useStyles //<- This useStyles is like the useStyles you get when you // call makeStyles but it doesn't return a classes object. } = createMakeAndWithStyles({ useTheme }); ``` `./MyComponent.tsx` ```tsx //Here we can import useStyles directly instead of generating it from makeStyles. import { useStyles } from "./makeStyles"; export function MyComponent(props: Props) { const { className } = props; const { cx, css, theme } = useStyles(); return ( hello world ); } ``` ``` -------------------------------- ### Naming Stylesheets with makeStyles Source: https://docs.tss-react.dev/api/makestyles Specify a name for your stylesheet to aid debugging and theme style overrides. ```APIDOC ## Naming Stylesheets with makeStyles ### Description To ease debugging you can specify a name that will appear in every class names. It is like the `option.name` in material-ui v4's `makeStyles`. It's also required for theme style overrides. ### Usage ```typescript const useStyles = makeStyles({ "name": "MyComponent" })({ "root": { "/*...*/" } }); //... then in your component: const { classes } = useStyles(); // classes.root will be a string like: "tss-xxxxxx-MyComponent-root" ``` ### Naming with Component Reference Usually, you want the name to match the name of the component you are styling. You can pass the name as the first key or a wrapper object. ```tsx export function MyComponent() { const { classes } = useStyles(); return

Hello World

; } const useStyles = makeStyles({ "name": { MyComponent } })({ "root": { "/*...*/" } }); //... then in your component: const { classes } = useStyles(); // classes.root will be a string like: "css-xxxxxx-MyComponent-root" ``` This prevents you from having to remember to update the label when you rename the component. You can also explicitly provide labels on a case by case basis if you do, your label will overwrite the one generated by `tss-react`. ``` -------------------------------- ### Component Usage with tss-react Source: https://docs.tss-react.dev/mui-global-styleoverrides Demonstrates how to use the 'MyComponent' and apply styles using tss-react's useStyles hook, including passing custom props and class names. ```tsx import { useStyles } from "tss-react/mui"; function App(){ const { css } = useStyles(); return ( ); } ``` -------------------------------- ### Using withStyles as an alternative to styled Source: https://docs.tss-react.dev/api/withstyles Replace the `styled` API with `withStyles` for enhanced type safety. This involves wrapping the component and its styles within the `root` key. ```typescript import { styled } from '@mui/material/styles'; import Popper from '@mui/material/Popper'; const StyledPopper = styled(Popper)({ border: '1px solid red', '& .Mui-autoComplete-listBox': { boxSizing: 'border-box', '& ul': { padding: 0, margin: 0 } }, "@media (max-width: 960px)": { color: "blue" } }); ``` ```typescript import { withStyles } from 'tss-react/mui'; import Popper from '@mui/material/Popper'; const StyledPopper = withStyles(Popper, { root: { border: '1px solid red', '& .Mui-autoComplete-listBox': { boxSizing: 'border-box', '& ul': { padding: 0, margin: 0 } }, "@media (max-width: 960px)": { color: "blue" } } }); ``` -------------------------------- ### MyComponent with Modern API (tss-react) Source: https://docs.tss-react.dev/mui-global-styleoverrides Defines a component using tss-react's modern API, demonstrating how to pass props and ownerState for dynamic styling within the `create` method. ```tsx import { tss } from "tss-react/mui"; export type Props = { className?: string; classes?: Partial["classes"]>; lightBulbBorderColor: string; } function MyComponent(props: Props) { const { className } = props; const [isOn, toggleIsOn] = useReducer(isOn => !isOn, false); const { classes, cx } = useStyles({ muiStyleOverridesParams: { props, "ownerState": { isOn } } }); return (

Div should have a border, background should be white

Light bulb should have black border, it should be yellow when turned on.

); } const useStyles = tss .withName("MyComponent") .create({ root: { border: "1px solid black", width: 500, height: 200, position: "relative", color: "black" }, lightBulb: { position: "absolute", width: 50, height: 50, top: 120, left: 500/2 - 50, borderRadius: "50%" } }); ``` -------------------------------- ### makeStyles without Props or State Source: https://docs.tss-react.dev/api/makestyles Define component styles without relying on props or state. ```APIDOC ## makeStyles() without Props or State ### Description If you don't need neither the theme nor any state or props to describe your component style you can pass-in an object instead of a callback. ### Usage ```typescript const useStyles = makeStyles()({ "root": { "backgroundColor": "pink" } }); //... then in your component: const { classes } = useStyles(); ``` ``` -------------------------------- ### Create tss instance with custom context (TypeScript) Source: https://docs.tss-react.dev/api/tss-usestyles Use createTss to initialize a tss instance with a custom context. The useContext function within the configuration receives the custom context, which can then be accessed in useStyles. ```typescript import { createContext } from "react"; import { createTss } from "tss-react"; const contextIsDarkMode = createContext(undefined); export function useContextIsDarkMode(){ const isDarkMode = useContext(contextIsDarkMode); if(isDarkMode === undefined){ throw new Error("You must wrap your app with a of contextIsDarkMode"); } return isDarkMode; } export const DarkModeProvider = contextIsDarkMode.Provider; export const { tss } = createTss({ useContext: function useContext(){ const isDarkMode = useContextIsDarkMode(); return { isDarkMode }; } }); ``` -------------------------------- ### makeStyles with Props and State Source: https://docs.tss-react.dev/api/makestyles Define component styles that depend on props and state. ```APIDOC ## makeStyles() with Props and State ### Description Your component style may depend on the props and state of the components. ### Usage ```typescript const useStyles = makeStyles<{ color: string; }>()( (_theme, { color }) => ({ "root": { "backgroundColor": color } }) ); //... then in your component: const { classes } = useStyles({ "color": "grey" }); ``` ``` -------------------------------- ### Styling an MUI component with withStyles Source: https://docs.tss-react.dev/api/withstyles Apply styles to an existing MUI component by passing it as the first argument to withStyles. This allows overriding the component's internal CSS rules. ```typescript import Button from "@mui/material/Button"; import { withStyles } from "tss-react/mui"; const MyStyledButton = withStyles(Button, { root: { backgroundColor: "grey" } text: { color: "red" }, "@media (max-width: 960px)": { text: { color: "blue" } } }); ``` -------------------------------- ### Import Fonts with GlobalStyles String Interpolation Source: https://docs.tss-react.dev/api/globalstyles When using string interpolation for the `styles` prop, you can dynamically import resources like fonts using `@import` rules. Ensure the `typography.fontFace.import` variable is correctly defined in your theme or configuration. ```tsx ``` -------------------------------- ### Applying Styles with useStyles Hook Source: https://docs.tss-react.dev/api/makestyles Utilize the useStyles hook to access cx, css, and theme for dynamic styling within your components, especially when only these utilities are needed. ```tsx //Here we can import useStyles directly instead of generating it from makeStyles. import { useStyles } from "./makeStyles"; export function MyComponent(props: Props) { const { className } = props; const { cx, css, theme } = useStyles(); return ( hello world ); } ``` -------------------------------- ### Replace useCssAndCx with useStyles Source: https://docs.tss-react.dev/update-to-v4 The `useCssAndCx` hook has been removed. Use the `useStyles` hook from `tss-react/mui` instead for similar functionality. ```diff -import { useCssAndCx } from "tss-react"; +import { useStyles } from "tss-react/mui"; -const { css, cx }= useCssAndCx(); +const { css, cx } = useStyles(); ``` -------------------------------- ### Define component styles with parameters Source: https://docs.tss-react.dev/ Define component styles using tss.withParams to specify dynamic parameters. The styles object can access these parameters and the theme context. ```typescript import { useState } from 'react'; import { tss } from './tss'; // NOTE: If you don't have a theme you can import { tss } from "tss-react"; export type Props = { className?: string; }; export function MyComponent(props: Props) { const { className } = props; const [color, setColor] = useState<'red' | 'blue'>('red'); const { classes, cx /*,myTheme*/ } = useStyles({ color }); //Thanks to cx, className will take priority over classes.root 🤩 return ( setColor('blue')} > hello world ); } const useStyles = tss .withParams<{ color: 'red' | 'blue'; }>() .create(({ myTheme, color }) => ({ root: { cursor: 'pointer', // The color of the text is red or blue depending on the state of the component color, // When mouse is hover, green border '&:hover': { border: `4px solid ${myTheme.primaryColor}`, }, // On big screen, a big black border '@media (min-width:48em)': { border: '10px solid black', } } })); ``` -------------------------------- ### Define and Use Styles in a Class Component Source: https://docs.tss-react.dev/api/withstyles Use `withStyles` to create a styled version of a class component. This is useful for migrating class components or when class-based components are preferred. Styles are accessed via `withStyles.getClasses(this.props)`. ```tsx import * as React from "react"; import { withStyles } from "tss-react/mui"; export type Props ={ className?: string; classes?: Partial>; isBig: boolean; }; class MyComponent extends React.Component { render() { const classes = withStyles.getClasses(this.props); return (
The background color should be different when the screen is small.
); } } const MyComponentStyled = withStyles( MyComponent, (theme, props) => ({ root: { backgroundColor: theme.palette.primary.main, height: props.isBig ? 100 : 50 }, span: { border: "1px solid red" }, "@media (max-width: 960px)": { root: { backgroundColor: "red" } } }) ); export default MyComponentStyled; ``` -------------------------------- ### MUI Theme Declaration for Global Style Overrides Source: https://docs.tss-react.dev/mui-global-styleoverrides Declares a MUI theme with global style overrides for 'MyComponent'. It shows how to access theme, ownerState, and custom props within the styleOverrides callback. ```typescript import { createTheme } from "@mui/material/styles"; import { ThemeProvider } from "@mui/material/styles"; const theme = createTheme({ components: { //@ts-ignore: It's up to you to define the types for your library MyComponent: { styleOverrides: { lightBulb: ({ theme, ownerState: { isOn }, lightBulbBorderColor })=> ({ border: `1px solid ${lightBulbBorderColor}`, backgroundColor: isOn ? theme.palette.info.main : "grey" }) } } } }); render( {/*...*/} ); ``` -------------------------------- ### Enable plugin in package.json for CRA Source: https://docs.tss-react.dev/detecting-unused-classes Configure ESLint within the package.json file to use the tss-unused-classes plugin and enable the unused-classes rule. This is for create-react-app projects. ```json { //... "eslintConfig": { "plugins": [ //... "tss-unused-classes" ], "rules": { "tss-unused-classes/unused-classes": "warn" } }, //... } ``` -------------------------------- ### Naming Stylesheets with makeStyles Source: https://docs.tss-react.dev/api/makestyles Specify a name for your stylesheet to aid debugging and theme style overrides. This name will be appended to generated class names. ```typescript const useStyles = makeStyles({ "name": "MyComponent" })({ "root": { "backgroundColor": "pink" } }); //... const { classes } = useStyles(); //classes.root will be a string like: "tss-xxxxxx-MyComponent-root" ``` -------------------------------- ### Inferring types for nested MUI component classes Source: https://docs.tss-react.dev/api/withstyles Demonstrates how withStyles can infer the types of nested, overwritable classes within an MUI component, such as the separator class in Breadcrumbs. ```typescript import Breadcrumbs from "@mui/material/Breadcrumbs"; import { withStyles } from "tss-react/mui"; const MyBreadcrumbs = withStyles( Breadcrumbs, (theme, props, classes) => { ol: { [`& .${classes.separator}`]: { color: theme.palette.primary.main } } } ); ``` -------------------------------- ### tss-react Core APIs Source: https://docs.tss-react.dev/api These are the core APIs exposed by the tss-react library for general styling purposes. ```APIDOC ## createTss ### Description The Modern API for creating styles, allowing you to provide a context such as a dynamic theme. ### Usage ```typescript import { createTss } from "tss-react"; const { tss } = createTss({ // Your dynamic theme context here }); ``` ``` ```APIDOC ## tss (Modern API - No Dynamic Theme) ### Description Use this API when you don't have a dynamic theme object to make available when writing your styles. ### Usage ```typescript import { tss } from "tss-react"; const useStyles = tss.withRouter(); // Example of using tss ``` ``` ```APIDOC ## keyframes ### Description A function to define CSS keyframes, as defined in `@emotion/react` and `@emotion/css`. ### Usage ```typescript import { keyframes } from "tss-react"; const spin = keyframes` from { transform: rotate(0deg); } to { transform: rotate(360deg); } `; ``` ``` ```APIDOC ## GlobalStyles ### Description A component provided by tss-react to define global styles for your application. ### Usage ```typescript import { GlobalStyles } from "tss-react"; ``` ``` -------------------------------- ### Insert Global CSS with GlobalStyles Source: https://docs.tss-react.dev/api/globalstyles Use this component to apply CSS rules globally, like setting the body background color or styling specific classes. It requires importing `GlobalStyles` and `useStyles` from 'tss-react'. The `styles` prop takes an object where keys are selectors and values are CSS properties. ```tsx import { GlobalStyles } from "tss-react"; import { useStyles } from "tss-react/mui"; function MyComponent() { const { theme } = useStyles(); return ( <>

This text will be cyan

); } ```