Sub topic 1
Components as functions that return JSX
React function components are JavaScript functions that return JSX, a syntax for describing the user interface. A component receives one argument: a props object containing inputs from its parent.
Prerequisites
This chapter assumes basic JavaScript functions, objects, destructuring, and arrow functions. You should also know basic HTML and have a basic understanding of React components.
Components and props
A parent passes props as attributes on a component. The child reads them from its parameter.
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default function App() {
return <Greeting name="Ada" />;
}Greeting receives { name: "Ada" }. Curly braces in JSX insert a JavaScript expression into the returned markup.
You can destructure the props object in the parameter list. Default values apply when the parent omits a prop.
function Avatar({ name, size = 48, rounded = true }) {
const style = {
width: size,
height: size,
borderRadius: rounded ? "50%" : 0
};
return <div style={style}>{name[0]}</div>;
}
export default function App() {
return (
<>
<Avatar name="Grace" />
<Avatar name="Linus" size={64} rounded={false} />
</>
);
}The first avatar uses the defaults. The second receives a number and a boolean because those values use curly braces.
Passing different values
Quoted JSX attributes are strings. Use curly braces for other JavaScript values, including objects, arrays, and functions.
function UserCard({ user, tags, onSelect }) {
return (
<article>
<h2>{user.name}</h2>
<p>{tags.join(", ")}</p>
<button onClick={onSelect}>Select</button>
</article>
);
}
export default function App() {
const user = { name: "Ada" };
const tags = ["React", "JavaScript"];
return (
<UserCard
user={user}
tags={tags}
onSelect={() => console.log(user.name)}
/>
);
}onSelect is a function prop. The child can call it in response to an event, while the parent decides what the action does.
Exercise
What value does size have when a parent renders <Avatar name="Ada" />?
Show answer
It has the default value 48, because the parent did not pass a size prop.