Deduplicate Title tags with React 19

Kent C. Dodds
Instructor

Kent C. Dodds

Let's learn how to dynamically manage title tags in React 19 applications. Rendering <title> dynamically is simple enough, however, a challenge arises when multiple title tags are present in the document, which can lead to issues with screen readers and search engine optimization (SEO). The solution presented involves ensuring that only one title tag is rendered at a time by using conditional rendering.

Also we need to make sure to have a single string within the title tag using a template literal, ensuring our HTML remains valid and optimized.

Transcript

[00:00] One of the cool things about these things being renderable by our React components is that now we can make them really dynamic. And so if I come down in here and I say, hey, you know what? When a ship has been selected, let's put that ship's name in the title. So we say title, ship name, and that works out really nicely. So now if I select one of these ships we're gonna see Galaxy Cruiser and Planet Hopper and so on and so forth.

[00:25] The problem is that now we have two titles in the document and while it's displaying properly there are screen readers that may have trouble with this, or there could be SEL problems with this because there's really only supposed to be a single title in the head. And so the solution to this is to make sure you don't ever render two of these at once. And so we're going to take this title and we're going to move it down as the opposite condition for this. And so now we only have one title showing up at a time and we have when we have one of these selected that will be showing up there as well. Additionally, if I wanted to say starship name, then starship deets right here, this technically doesn't work either because you need to have just a single string inside of that title.

[01:12] And so what we would do here is turn it into a template literal. And now we're going to get our desired outcome here. So it's important that the title tag have just as its only child a single string. And also important that you don't render two title tags at the same time. In our case, we're rendering them as opposite conditions.

[01:36] So that way, we don't ever end up with invalid HTML in our output.