Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use antd theme tokens in my custom component?

I want to use antd theme tokens to style my custom component? May be there is an emotion-like way:

// style.ts
export default createStyles((token) => ({
  foo: {
    color: token.colorPrimary,
  }
})

// index.tsx
import styles from './style';

const FooBar = () => {
  return (
    <div className={styles.foo}>
      FooBar
    </div>
  );
};

Or maybe there is a better way to do it? There is practically nothing in the docs except useToken and use in style directly.

like image 665
Maxim Lanin Avatar asked Oct 15 '25 08:10

Maxim Lanin


1 Answers

You can import theme from antd and use it as a hook:

import { theme as antdTheme } from 'antd'

function MyComponent() {
  const { useToken } = antdTheme
  const { token: theme } = useToken() 

  // now use it
  return (<div 
    style={{
      color: theme.colorPrimary
    }}>
      styled div
  </div>)
}

Or you can create a styles file (keeping your styles separated from your components/functions) and use it like this:

// styles.ts
import { CSSProperties } from 'react'
import { theme as antdTheme } from 'antd'

// if you use TS you must declare types here
type StylesType = {
  DivStyle: CSSProperties
  OtherComponentStyle: CSSProperties
}

function Styles(): StylesType {
  const { useToken } = antdTheme
  const { token: theme } = useToken()

  const DivStyle = {
    color: theme.colorPrimary
  }

  ... other components


  return {
    DivStyle,
    ... other components
  }
}

export default

And use it like this:

// MyComponent.tsx
import Styles from 'path/to/styles'

function MyComponent() {
  const S = Styles()

  // now use it
  return (
    <div 
      style={S.DivStyle}
    >
        styled div
    </div>
  )
}
like image 194
luicfrr Avatar answered Oct 16 '25 21:10

luicfrr