Skip to content

Instantly share code, notes, and snippets.

@edoves
Last active November 29, 2024 08:48
Show Gist options
  • Save edoves/36dbc14215f19ec24e15bf9805736b6d to your computer and use it in GitHub Desktop.
Save edoves/36dbc14215f19ec24e15bf9805736b6d to your computer and use it in GitHub Desktop.

ReactJS Component

  • Heading Tag(dynamic)
  • Img Tag

Heading Tag

import React from 'react'

type HeadingProps = React.HTMLAttributes<HTMLHeadingElement> & {
  as: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'
  text: string
  className?: string
}

export default React.forwardRef<HTMLHeadingElement, HeadingProps>(
  ({ className, as, text, ...props }, ref) => {
    const Tag = as

    return React.createElement(Tag, { className, ref, ...props }, text)
  }
)

Example of using forward ref to img element

What we trying to achieve here is that when we use the logo component we stil get the classes of tailwind if we dont do the forwardRef the component does not know or do not do the auto suggest classes

/logo.tsx

type ImgProps = React.ImgHTMLAttributes<HTMLImageElement> & {
  imgSrc: string
}

export default React.forwardRef<HTMLImageElement, ImgProps>(
  ({ className, imgSrc, ...props }, ref) => {
    return <img src={imgSrc} className={className} ref={ref} {...props} />
  }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment