React Components: Building UIs with Code
Introduction
In the old days of web development, building a website was a fragmented process. You wrote HTML files for structure and then used JavaScript to manually manipulate those elements.
React changes the game. Instead of treating HTML and JavaScript as separate worlds, React allows you to write your UI as JavaScript. This is where React Components come in.
"A React component is simply a JavaScript function that returns a piece of UI using JSX."
The Rules of React Components
To write a valid React component, you must follow these three fundamental rules:
- Capitalization: Your component name must start with a Capital Letter (e.g.,
App,Navbar,UserCard). If you start with a lowercase letter (likeapp), React will think it is a standard HTML tag and your code won't work. - The One Return Rule: A component function must return a single root element. If you want to return multiple tags, you must wrap them in a
<div>, a<section>, or a React Fragment (<>...</>). - JSX (JavaScript XML): It looks like HTML, but it is actually a syntax extension for JavaScript. JSX is eventually compiled into real DOM elements that the browser can understand.
A Practical Example
Here is what a basic functional component looks like in code:
// This is a functional componentfunction App() {return (<div><h1>Hello React</h1><p>Building UIs with components is fun!</p></div>);}export default App;
Why Use Components?
The power of components lies in reusability. You can build a Button component once and use it dozens of times across your application with different colors or text. This makes your code cleaner, easier to test, and much faster to maintain.
Summary FAQ
What is a React Component?
A reusable JavaScript function that defines how a part of the user interface should look.
Do I have to use JSX?
While not strictly mandatory, JSX is the standard way to write React apps because it makes the UI structure much easier to read and write.
