Image for post
Image for post

Create a simple react-head component using react portals

Stoyan Delev
Feb 5, 2019 · 1 min read

I like React and its ecosystem but I don’t like the idea of installing hundreds of dependencies for everything. And I don’t want to use any extra libraries especially when I am building things like PWA, every byte counts so I always try to avoid “npm install another-library”

So for one of my projects, I needed Head component, similar to React Head or React Helmet but I didn’t like the API of one and the size of another. So I was looking for simple and better for my case solution.

Using React Portals seems quite a good idea and doesn’t require any external dependencies. All you need to do is create a portal with document head as a root and render inside that portal.

Afterwards, you can use it like so:

I also prefer creating a helper component for that:

and I use it like:

That is all.
No dependency simple solution.
I guess you still might consider some of the mentioned libraries if you need more advanced functionality, SSR for example.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store