
Step 3 - Learn about Props so that you can reuse components
19 January, 2023
5
5
1
Contributors
What exactly are props in React
Props are the second most important things you need to remember in React.
Props in React are used to pass data from one component to another. They are similar to state in that they are used to keep track of data, but unlike state, props are passed from one component to another rather than being updated within the component itself. Props can be used to customize and configure components, allowing for a more dynamic and flexible user interface.
React provides an API for managing state called the Context API. This API makes it easy to share data between components, allowing for efficient and consistent updates across the application. The Context API usually comes into the picture when we want to share some information globally, like themes.
An example for props in React
Here’s an example for props in a React class component. In all the other references in this roadmap, we will learn how props work with a functional component.
class MyComponent extends React.Component {
render() {
return (
<div>
<p>Name: {this.props.name}</p>
<p>Age: {this.props.age}</p>
<p>Email: {this.props.email}</p>
</div>
);
}
}
// Use the MyComponent component and pass in some props
<MyComponent name="John" age={30} email="john@example.com" />
In this example, the MyComponent
component has three props: name
, age
, and email
. The parent component is using the MyComponent
component and passing in the values for these props.
Inside the MyComponent
component, you can access the props using this.props
. In the example above, we are using the props to render the name
, age
, and email
values in the UI.
Point to remember about props: Props are read-only
Props are read-only and cannot be modified inside the component. If you need to update a value based on user input or some other event, you should use state instead.
Even if you modify props inside of a component, they would have no effect on the parent component that actually supplied the props and neither would the React component re-render because the props were modified internally.
This distinction between state and the props is the one point all beginner React developers must keep in mind.