Need the same kind of link in several places? Make it a component. A React component is a reusable piece of a user interface; each use can receive different properties, or props. Components can contain HTML elements and other components, so a small link can become part of a menu or a larger application. section 1.0 section 4.1.1
Make a link component
function MenuItem({ href, label }) { return <li><a href={href}>{label}</a></li>; } function Menu() { return <ul><MenuItem href="/about/" label="About" /></ul>; } MenuItem is a functional component: a JavaScript function that returns UI output. Menu uses its capitalized name as a JSX tag and supplies href and label as props. The function destructures those values from its props argument, then uses them in the returned JSX. A second MenuItem can reuse the same definition with different values. section 4.1.1 section 4.1.2
Destructuring is optional. You can write function MenuItem(props) and read props.href and props.label instead. JSX is also optional: React.createElement can create the same kinds of elements, though JSX makes nested components easier to read. Pass child content between a component’s tags; it arrives through the specially named children prop. section 4.1.1 section 4.1.2 section 2.9
Listing 4.2 Menu application using functions
import "./App.css";
function App() { #1
return (
<main>
<Menu />
</main>
);
}
function Menu() { #1
return (
<nav className="navbar">
<h1 className="title">TheMenuCompany</h1>
<ul className="menu">
<MenuItem label="Home" href="/" />
<MenuItem label="About" href="/about/" />
<MenuItem label="Blog" href="/blog" />
</ul>
</nav>
);
}
function MenuItem(props) { #2
return (
<li className="menu-item">
<a className="menu-link" href={props.href}>
{props.label}
</a>
</li>
);
}
export default App;
Follow the complete menu from App through Menu to three MenuItem instances, each supplied with its own label and destination. section 4.1.1
A component can also be defined as a class with a render method. For a simple component, replacing that method with a function and replacing this.props with a props argument gives a shorter definition. Functional components are the usual choice, but classes remain supported. An error boundary is one reason to use a class; an established class-based codebase may be another. Hooks brought functional components capabilities once associated with classes. section 4.4.1 section 4.0 section 4.3









