A prop is any input that you pass to a React component. Props are given as an object and are the first argument to a component function, like this:
Notice the syntax to pass a prop to a component. The prop name is the attribute name, and the prop value is the attribute value. In this example, we pass the name
prop with the value "Ali"
to the Greeting
component. You can pass any number of props to a component. All the props are aggregated into a single object and passed as the first argument to the component function.
You can use object destructuring syntax to extract the properties from the props
object:
Alternatively, you can destructure the properties directly in the function signature:
Aside: In class components, props are passed to the class constructor.
Props are Read-Only: You should never modify the props object directly. React components are meant to be pure functions that do not modify their inputs. If you need to change the value of a prop, you should do so in the parent component and pass the new value down as a new prop. Treat props as read-only.
Here is a contrived example of how you might try to modify a prop:
This is anti-pattern and should be avoided. Instead, you should create a new prop in the parent component and pass it down:
React aggregates all the props into a single object. This makes it easy to pass many props to a component, but it can also make it easy to pass the wrong props or forget to pass required props. If you use TypeScript, you can use interfaces (or types) to define the shape of the props object. If you use JavaScript, you can use the prop-types
library to document and type-check the props.
If you are using TypeScript, you can define an interface to describe the shape of the props object:
TypeScript will check that the props passed to the Greeting
component match the GreetingProps
interface.
If you are using JavaScript, you can use the prop-types
library to document and type-check the props.
First, install it:
Then, import and use it:
Notice that we attached the propTypes
object to the Greeting
function. This object defines the types of the props that the component expects. In the propTypes
object, we define the name
prop as a required string. If the name
prop is not passed or is not a string, React will log a warning in the console.