π£ 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

Core UX and Software Engineer.
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! π»β¨





