Skip to main content

Use semantic HTML elements for accessible document structure

Medium
accessibilityreacthtml

What

This practice applies when creating React components that render page layouts. Developers must ensure that each section of the document uses semantic HTML elements like <header>, <nav>, <main>, and <footer> and that there is exactly one visible <main> element to maintain accessibility.

Why

Using semantic HTML ensures that assistive technologies can accurately interpret the structure of your page, improving navigability and compliance with accessibility standards such as WCAG and ARIA. Incorrect or non-semantic markup may confuse users relying on these technologies.

Fix

Replace generic HTML elements or misused semantic tags with the correct semantic elements. Ensure that only a single <main> element is visible and additional main elements, if present, are properly hidden using attributes like hidden or appropriate styles.

Examples

Example 1:

Positive

The code uses semantic HTML elements correctly, with one visible <main> element ensuring proper document structure and accessibility.

import React from 'react';

const PageLayout: React.FC = () => {
return (
<>
<header>
<h1>Site Title</h1>
</header>
<nav>
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
<main>
<section>
<h2>Main Content</h2>
<p>This is where the primary content goes.</p>
</section>
</main>
<footer>
<p>© 2023 Your Company</p>
</footer>
</>
);
};

export default PageLayout;

Negative

The code fails by using non-semantic <div> elements instead of <header>, <nav>, and <footer> and includes two visible <main> elements, which confuses assistive technologies.

import React from 'react';

const PageLayout: React.FC = () => {
return (
<>
<div className="header">
<h1>Site Title</h1>
</div>
<div className="nav">
<ul>
<li><a href="/home">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</div>
<main>
<section>
<h2>Main Content Part 1</h2>
<p>This is the first main content section.</p>
</section>
</main>
<main>
<section>
<h2>Main Content Part 2</h2>
<p>This is the second main content section, which should be hidden.</p>
</section>
</main>
<div className="footer">
<p>© 2023 Your Company</p>
</div>
</>
);
};

export default PageLayout;