In React, function components allow you to break down the UI into reusable elements. These components use JSX to create a virtual DOM structure, which React efficiently converts into the real DOM.
Think of function components as small, modular building blocks—like LEGO bricks—that you can combine to build complex applications.
A function component is a simple JavaScript function that returns JSX.
function NavBar() {
return (
<nav>
<h1>Pet App</h1>
<ul>
<li className="selected">
<a href="/pets">Pets</a>
</li>
<li>
<a href="/owners">Owners</a>
</li>
</ul>
</nav>
);
}
This function returns a JSX structure that represents a navigation bar.
To convert the JSX into real DOM, use React's render method.
// Get the root DOM node
const rootElement = document.getElementById('root');
// Render the component
ReactDOM.createRoot(rootElement).render(<NavBar />);
This renders the NavBar component inside the real DOM element with the ID root.
React requires components to return something. If a component does not need to render anything, return null instead of undefined.
const str = "hello";
function ExampleComponent() {
if (str === "hello") return null;
return <div>World!</div>;
}
If str is "hello", the component returns null and renders nothing.
React allows conditional rendering using ternary operators or logical && operators.
function ConditionalRender({ condition }) {
return (
<>
{condition ?
<h1>Shows when condition is truthy.</h1> :
<h1>Shows when condition is falsy.</h1>
}
{condition &&
<p>You will see this only if condition is truthy.</p>
}
</>
);
}
JSX evaluates condition and dynamically renders the appropriate content.
Be careful: falsy values like 0 will still render, so ensure your conditions explicitly check for booleans.
React allows components to be composed by nesting them inside each other.
function NavLinks() {
return (
<ul>
<li className="selected">
<a href="/pets">Pets</a>
</li>
<li>
<a href="/owners">Owners</a>
</li>
</ul>
);
}
function NavBar() {
return (
<nav>
<h1>Pet App</h1>
<NavLinks />
</nav>
);
}
Here, NavBar renders the NavLinks component inside of it, keeping the code modular and readable.
As applications grow, it’s best to keep each component in its own file for better organization.
NavLinks.jsxfunction NavLinks() {
return (
<ul>
<li className="selected">
<a href="/pets">Pets</a>
</li>
<li>
<a href="/owners">Owners</a>
</li>
</ul>
);
}
export default NavLinks;
NavBar.jsximport NavLinks from './NavLinks';
function NavBar() {
return (
<nav>
<h1>Pet App</h1>
<NavLinks />
</nav>
);
}
export default NavBar;
Using separate files for components improves maintainability and reusability.
NavBar, NavLinks).export default for a single component per file.While keeping one component per file is a common practice, some cases may require multiple related components in one file.
In this tutorial, you learned:
&&.By structuring your components well, you can build efficient and reusable React applications.