GʀᴜᴍᴘʏCᴀᴛ
GʀᴜᴍᴘʏCᴀᴛ

Reputation: 8898

Next.js & TailwindCSS how to re-use styles on a component in the same component file?

Working on my first Next.js 14 project and quickly found out the theme I'd authored in Chakra UI will not work with server components (reference: Support for NextJS 14) until Chakra UI version 3 is released and as I'm not wanting to use the use client for every component I'm going to learn TailwindCSS and re-write everything.

That said I have a component in Chakra UI:

interface DefStyles {
  fontFamily: string
  fontWeight: string
  textAlign: string
  mb: string
  mx: string
  maxWidth: string
}

const defStyles: DefStyles = {
  fontFamily: 'heading',
  fontWeight: 'semibold',
  textAlign: 'center',
  mb: '4',
  mx: '5',
  maxWidth: 'lg',
}

interface Props {
  foo: string
  bar: string
}

// stripped component
export default function ChakraComponent({ foo, bar }: Props) {
  return (
    <Flex
      justify="center"
      w="full"
      direction="column"
      align="center"
    >
      <Text as="h3" color="primary.500" fontSize="xs" {...defStyles}>
        {foo}
      </Text>
      <Text color="white" {...defStyles}>
        {bar}
      </Text>
    </Flex>
  )
}

that I'm spreading some default styles:

const defStyles: DefStyles = {
  fontFamily: 'heading',
  fontWeight: 'semibold',
  textAlign: 'center',
  mb: '4',
  mx: '5',
  maxWidth: 'lg',
}

when I create this in TailwindCSS:

export default function TailwindComponent({ foo, bar }: Props) {
  return (
    <div className="p-6 w-full flex justify-center flex-col items-center">
      <h3 className='text-sm text-primary'>{foo}</h3>
      <p className="text-white">{bar}</p>
    </div>
  )
}

I'm stuck trying to figure out how to re-use some common styles. I've read about:

Research:

what is the correct way I can re-use this on a component level in the same component file?

Upvotes: 0

Views: 246

Answers (1)

Jack McBride
Jack McBride

Reputation: 90

Create a variant of the Text component. So a new component called <MyNewText> which has those styles in the className via tailwind

Upvotes: 0

Related Questions