How do we break HTML semantics by using <div> in ReactJs (Jsx)

Viewed 619

ReactJs docs says:

Sometimes we break HTML semantics when we add <div> elements to our JSX to make our React code work, especially when working with lists (<ol>, <ul> and <dl>) and the HTML <table>. In these cases we should rather use React Fragments to group together multiple elements.

Ref: https://reactjs.org/docs/accessibility.html

I would really like to understand that how do we break the HTML semantics by using <div> or the other elements mentioned above and how does the React Fragments is an improvement over that.

Also, I would like to understand that what are the problems that might arise by breaking of such semantics.

Thanks in advance.

1 Answers

Imagine that you have a <ul id="root"> element and you want to insert in it a couple of <li> tags. React element can only have single root node, so the first thing which come to mind is to wrap all <li> tags in a <div> e.g. the following:

  const element = () => {
     return (
       <div>
         <li>Some list item</li>
         <li>Some other list item</li>
       </div>
     );
  };

  ReactDOM.render(element, document.getElementById('root'));

Which will result in the following HTML:

<ul id="root">
    <div>
        <li>Some list item</li>
        <li>Some other list item</li>
    <div>
</ul>

Now we successfully broke the HTML semantics, it is not valid HTML to have a div directly inside a ul element. One way to avoid that is by using React Fragments:

  const element = () => {
     return (
       <Fragment>
         <li>Some list item</li>
         <li>Some other list item</li>
       </Fragment>
     );
  };

  ReactDOM.render(element, document.getElementById('root'));

The Fragment doesn't insert extra HTML tag which won't broke the semantics. Here is the resulting HTML

<ul id="root">
    <li>Some list item</li>
    <li>Some other list item</li>
</ul>
Related