๐Ÿ“ฃ  Creating Reusable Container Components in Next.js ๐Ÿš€

๐Ÿ“ฃ Creating Reusable Container Components in Next.js ๐Ÿš€

How to successfully create a reusable container component in Next.js that gets rendered as an HTML tag on the browser

ยท

2 min read

I wanted to share a little insight on how I successfully created a reusable container component in Next.js that takes the props for an HTML tag type and gets rendered as that tag on the browser. ๐ŸŽ‰

๐Ÿ“ฆ Before, I used to declare the HTML tag and then create the component separately. However, I discovered a more elegant solution that allows me to dynamically render different HTML tags with just a single component.

๐Ÿ”ฅ Let me introduce you to the magical Container component I created:

const Container = ({
  children,
  className,
  tag: Tag = 'div',
}: {
  children: React.ReactNode;
  className?: string;
  tag?: keyof JSX.IntrinsicElements;
}) => {
  return <Tag className={`container ${className}`}>{children}</Tag>;
};

export default Container;

๐ŸŒŸ Here's how it works:

1๏ธโƒฃ The Container component accepts three props:

  • children: The content to be rendered inside the container.

  • className: An optional class name for custom styling.

  • tag: The HTML tag type to be rendered (default is 'div').

2๏ธโƒฃ By passing the desired HTML tag as the tag prop, the Container component dynamically renders that tag on the browser.

๐ŸŽ Here's an example of how I use the Container component:

<Container className="header-container" tag="header">
  {/* Content */}
</Container>

๐ŸŽ‰ This code snippet would render the Container component as a <header> tag with the specified class name, allowing for easy styling and flexibility.

๐Ÿš€ With this approach, I've achieved a delightful level of reusability and flexibility in my Next.js projects. Now, I can reuse the same Container component with different HTML tags effortlessly.

โœจ Feel free to give it a try and level up your Next.js development!


I hope you find this insight helpful and inspiring! Let's create delightful user experiences together with reusable components. Feel free to share your thoughts and experiences in the comments below. ๐Ÿ™Œ

Follow me on LinkedIn

Happy coding! ๐Ÿ’ปโœจ

ย