In React, props (short for "properties") are a way to pass data and behavior down from a parent component to a child component. Props are read-only, meaning that a child component cannot modify the props it receives from its parent. Instead, a child component can use the props to render its UI or trigger certain behavior.
React props can be of any data type, including primitives (such as numbers and strings), objects, arrays, and even functions. However, it's a good practice to define the types of props that a component expects to receive, both for documentation purposes and for type checking with tools like TypeScript or Flow.
Here are some common types of props in React:
- String props: These are props that contain string values. For example:
javascriptCopy codefunction Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="John" />
- Number props: These are props that contain numeric values. For example:
javascriptCopy codefunction Counter(props) {
return <p>{props.count}</p>;
}
<Counter count={42} />
- Boolean props: These are props that contain true/false values. For example:
javascriptCopy codefunction Checkbox(props) {
return <input type="checkbox" checked={props.checked} />;
}
<Checkbox checked={true} />
- Object props: These are props that contain objects. For example:
javascriptCopy codefunction User(props) {
return (
<div>
<h2>{props.user.name}</h2>
<p>{props.user.email}</p>
</div>
);
}
<User user={{ name: 'John', email: 'john@example.com' }} />
- Array props: These are props that contain arrays. For example:
javascriptCopy codefunction List(props) {
return (
<ul>
{props.items.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
<List items={[
{ id: 1, text: 'Item 1' },
{ id: 2, text: 'Item 2' },
{ id: 3, text: 'Item 3' },
]} />
In addition to these basic types, React also provides a way to define custom prop types using the propTypes
property. This property allows you to define the type and shape of each prop that a component expects to receive. Here's an example:
javascriptCopy codeimport PropTypes from 'prop-types';
function Person(props) {
return (
<div>
<h2>{props.name}</h2>
<p>{props.age}</p>
</div>
);
}
Person.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
In this example, we define a Person
component that expects two props: name
and age
. We use the PropTypes
object to define the type and shape of each prop, and we also specify that each prop is required (using the isRequired
method). This allows us to catch errors early if a prop is missing or of the wrong type.