Sub topic 1
Components are functions that return UI
Prerequisites
Assume you know modern JavaScript functions, destructuring, array methods, ES modules, and basic HTML elements and attributes.
Components are functions that return UI
A React component is a JavaScript function that returns a description of user interface (UI). Component names start with an uppercase letter. React uses that capitalization to distinguish a component from a built-in HTML element.
function Greeting({ name }) {
return <h1>Hello, {name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}Greeting receives an object called props. The parameter destructuring extracts its name property. When App renders <Greeting name="Ada" />, React calls the function with { name: "Ada" }.
Writing markup with JSX
JSX is a JavaScript syntax extension that resembles HTML. It lets a component describe nested elements directly in its return statement. A component must return one expression. Use a parent element or a fragment when the result has multiple siblings.
function Welcome() {
return (
<main>
<h1>Welcome</h1>
<p>Choose an option to continue.</p>
</main>
);
}JSX is stricter than HTML. Close every element, including elements such as <img />, and use {/* comment */} for comments inside JSX.
Using JavaScript inside JSX with curly braces
Place a JavaScript expression between { and }. Expressions produce values, so variables, property access, function calls, and conditional expressions work there.
function Score({ points }) {
const message = points >= 10 ? 'You passed.' : 'Keep practicing.';
return (
<p>
Score: {points}. {message}
</p>
);
}Do not put statements such as if directly inside JSX. Compute values before the return, or use a conditional expression.
Attributes in JSX: `className`, `style`, and camelCase
JSX attributes use JavaScript-friendly names. Use className instead of HTML’s class, and use camelCase names such as tabIndex and onClick.
The style attribute receives a JavaScript object. CSS property names become camelCase, and numeric values usually represent pixels.
function Profile() {
return (
<img
className="avatar"
src="/ada.png"
alt="Ada Lovelace"
style={{ width: 64, borderRadius: 8 }}
/>
);
}The outer braces embed a JavaScript expression. The inner braces create the object passed as the style value.
Exercise
Why does style={{ color: 'navy' }} contain two pairs of braces?
Show answer
The outer braces embed a JavaScript expression in JSX. The inner braces create the style object.