Using Props in React.pdf
Document Details
Uploaded by Deleted User
Tags
Full Transcript
Using Props in React 1. What are Props? Props (short for properties) are a way to pass data from one component to another in React. They are read-only and allow you to customize the behavior and appearance of components. 2. Creating a Parent Component First, let’s create a parent component that wil...
Using Props in React 1. What are Props? Props (short for properties) are a way to pass data from one component to another in React. They are read-only and allow you to customize the behavior and appearance of components. 2. Creating a Parent Component First, let’s create a parent component that will pass data to a child component using props. import React from 'react'; import ChildComponent from './ChildComponent'; function ParentComponent() { const message = 'Hello from the Parent Component!'; return ( Parent Component ); } export default ParentComponent; In this example, `ParentComponent` is passing a `message` prop to `ChildComponent`. The value of the `message` prop is a string: 'Hello from the Parent Component!' 3. Creating a Child Component Next, create a child component that will receive the `message` prop from the parent component and display it. import React from 'react'; function ChildComponent(props) { return ( Child Component {props.message} ); } export default ChildComponent; In `ChildComponent`, the `message` prop is accessed via `props.message` and displayed within a `` tag. This allows the child component to display data that is passed from the parent component. In order to run these Parent and Child components, you need to import and call the ParentComponent in the App.jsx 4. Using Props to Pass Dynamic Data Props can also be used to pass dynamic data to child components. For example, you can pass user data, configuration settings, or any other data that the child component needs to function. import React from 'react'; import UserProfile from './UserProfile'; function App() { const user = { name: 'John Doe', age: 30, email: '[email protected]' }; return ( User Profile ); } export default App; In this example, the `App` component is passing a `user` object to the `UserProfile` component. The `user` object contains data about a user, such as their name, age, and email. import React from 'react'; function UserProfile(props) { return ( {props.user.name} Age: {props.user.age} Email: {props.user.email} ); } export default UserProfile; The `UserProfile` component receives the `user` object as a prop and displays the user's name, age, and email. Conclusion Props are a fundamental concept in React that allow you to pass data between components, making your applications more dynamic and reusable. Understanding how to use props effectively is key to mastering React development.