๐ฃ 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
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! ๐ปโจ