JSX Self-closing tag not rendering

In the exercise Animal Fun Fact I noticed that using a self-closing h1 does not render the text in the browser. While normal open and close tags do.

import { animals } from './animals';
import React from "react";
import ReactDOM from "react-dom";

const title = "";
const animalFacts = <h1/>{title===""? "Click an animal for a fun fact" : title};

ReactDOM.render(animalFacts, document.getElementById("root"));

Is it a bug?

Hi @usernamegiapreso
maybe I don’t understand what you’re trying to do here. But <h1> is not a self-closing tag. And even if it were, your title would then be an attribute of h1. Now animalFacts is just an invalid closing tag and a string.

Hey there @mirja_t!
I mean this: Can I use self-closing tag syntax for any HTML elements I use in JSX? says that any HTML element can be self-closing in JSX. Are h elements excluded? Seems weird.

I’m an idiot, I missed the part about the children :man_facepalming:

Now when would this be useful? Making a self-closing element is useful when said element has no children, this should be the only time we use self-closing syntax for HTML elements that are normally not self-closing.

Hmm, from what I’ve learnt so far, we’d use self closing tags mainly for components. And they would render to valid html. And the h1 in your title is supposed to be rendered as normal html. The article linked doesn’t mention a use case for that self closing html, unfortunately.

Cheers, I checked the React docs and in order to use the self-closing syntax for the tags it’s required that the elements must not have children.

You can also use the self-closing form of the tag if there are no children. So:

<div className="sidebar" />

compiles into:

  {className: 'sidebar'}
1 Like

Ah ok. I ignored the part until now. Thank you!

1 Like