Skip to main content

Command Palette

Search for a command to run...

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

Updated
β€’2 min read
πŸ“£  Creating Reusable Container Components in Next.js πŸš€
D

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! πŸ’»βœ¨