You can pass pieces of information as properties to React components. These are called props.
function Header({ title }) { return <h1>{`Cool ${title}`}</h1>;}
Note
JSX elements directly inside a map() call always need keys!
Keys tell React which array item each component corresponds to, so that it can match them up later. This becomes important if your array items can move (e.g. due to sorting), get inserted, or get deleted. A well-chosen key helps React infer what exactly has happened, and make the correct updates to the DOM tree.
Naming
The variable does not need to be named
props
You can name the parameter anything you like because it is simply a JavaScript function parameter that receives an object containing your passed properties.
How it works:
- Any name works: You can name it
parameters,data,attributes, or even a single letter likep.
// These all work exactly the same way:
function UserProfile(props) { return <h1>{props.name}</h1>; }
function UserProfile(parameters) { return <h1>{parameters.name}</h1>; }
function UserProfile(data) { return <h1>{data.name}</h1>; }
- Destructuring (Common Practice): Most developers prefer to destructure the object right in the function parameter list so they don’t even have to use the word
propsor writeprops.repeatedly:
// Instead of props.name and props.age
function UserProfile({ name, age }) {
return <h1>{name} is {age} years old.</h1>;
}
Conventionally, many developers use props as a shorthand for properties, but JavaScript doesn’t enforce or care what you call it.