React JS Training Course Online
- 21k Enrolled Learners
- Weekend
- Live Class
Props in React stands for “properties.” Props are objects where values of attributes of a tag are maintained. Actually, quite near to HTML attributes. It is used to pass data from one component to another. Props are ready-only components, which means once data is submitted via props into another element, it can’t be modified further. Instead, they are immutable and can only be changed by changing the parent component that owns the props.
So, to pass props into a component, you would use the same syntax as HTML attributes. For example, you could add a “brand” attribute to a Car element like this: const element = <Car brand=”Ford” />; It means that the argument arrives in the component as an object of props. Logically, you would then use this props object from inside the component to get access to the data passed. For example, you would use the brand attribute like this: function Car(props) { return <h2>I am a { props.brand }! </h2>; }.
The way on how you pass data from one component to another as parameters is also a Prop.
For example, you can send the “brand” property from the Garage component to the Car component like this:
function Car(props) { return <h2>I am a { props.brand }!</h2>; } function Garage() { const carName = "Ford"; return ( <> <h1>Who lives in my garage? <Car brand={ carName } /> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Garage />); You can even pass an object as a prop: function Car(props) { return <h2>I am a { props.brand.model }!</h2>; } function Garage() { const carInfo = { name: "Ford", model: "Mustang" }; return ( <> <h1>Who lives in my garage? <Car brand={ carInfo } /> </> ); } const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<Garage />);
Note that React props are read-only, so you’re going to get an error if you try to change their value.
React PropTypes are a way to specify what props a component expects. It detects bugs and greatly improves the overall quality of your application, including error messaging. PropTypes exports a range of validators that you can use to make sure the data that you receive is valid.
Check below the instance of how to use PropTypes:
import PropTypes from 'prop-types'; function MyComponent(props) { // . } ``` MyComponent.propTypes = { name: PropTypes.string.required, age: PropTypes.number, onClick: PropTypes.func, isAdmin: PropTypes.bool, items: PropTypes.arrayOf(PropTypes.string), callback: PropTypes.func.required, };
In the example below, we would import the PropTypes library and then we would define the expected prop types for our MyComponent component. We could state, for instance, that name should be a string, and it is required; age—to be a number; onClick and callback—to be functions; isAdmin—to be a boolean; and items—an array of strings.
In the case where any prop does not have some corresponding type, a warning will show in the console; this is quite useful in ensuring that bugs are detected early enough in development and the components are used correctly.
By default, props enable the transfer of default values to a component’s props. This is pretty helpful in a case whereby you want to have some value on some certain prop, even if no value is provided.
function MyComponent(props) { return ( <div> <h1>Hello, {props.name}!</h1> <p>You are {props.age} years old.</p> </div> ); } MyComponent.defaultProps = { name: 'John Doe', age: 30, };
}
MyComponent.defaultProps = {
name: ‘John Doe’,
age: 30,
In this example, default props are defined for the name and age props. When the component is used with no values provided for these props, the default values will be used.
Variables or functions may also be used to define default props:
function getDefaultName() { return 'John Doe'; } MyComponent.defaultProps = { name: getDefaultName(), age: 30, };
It generates the default value of the name prop in our example, which is returned by the function ‘getDefaultName’.
It generates the default value of the name prop in our example, which is returned by the function ‘getDefaultName’.
In React, state and props are both objects, but they serve completely different purposes. Props are used when we want to pass the data from the parent component into the child component, whereas the state is used for managing the interior state of a component.
<span style="font-weight: 400;">This is an example of using state and props together:</span> function ParentComponent() { const [message, setMessage] = useState('Hello, world!'); return ( <div> <h1>{message}</h1> <ChildComponent message={message} /> </div> ); } function ChildComponent(props) { return ( <div> <p>{props.message}</p> </div> ); }
The state of the message variable is managed in the ParentComponent in this example using the useState hook. Afterwards, it passes the chosen state to ChildComponent as a message prop. At last, ChildComponent just displays the provided message prop.
Additionally, you can change the state in the parent component and then pass that state to the child component as a prop:
function ParentComponent() { const [message, setMessage] = useState('Hello, world!'); const handleClick = () => { SET_MESSAGE('Goodbye, world!'); } ; return ( <div> <h1>{message}</h1> <button onClick={handleClick}>Change Message</button> <ChildComponent message={message} /> </div> ); } function ChildComponent(props) { return ( <div> <p>{props.message}</p> </div> ); }
In the above example, the handleClick function is triggered when the button is clicked. But what it really does is update the message state with setMessage and then pass the message prop to the ChildComponent with the updated message.
Props, in React, are the properties of a React component. They represent a means to transfer data from a parent component to a child component. Props could be of any data type, from strings to numbers strings to numbers, booleans, arrays, objects, or even functions.
The example below identifies how one can define props for a React component:
function MyComponent(props) { return ( <div> <h1>{props.title}</h1> <p>{props.description}</p> <button onClick={props.onClick}>Click me</button> </div> ); }
Here is an example where MyComponent takes three props: title, description, and onClick. The title and description props are used to display text. The onClick prop is a function that is called when the button gets clicked.
Here, the App component passes along props for title, description, and onClick to the MyComponent component. The onClick prop is a function itself. Being called (here at button click), it shows an alert.
Prop It can also be used to pass complex data structures such as arrays and objects to components.
<li key={index}>{item}</li> )) </ul> ); } function App() { const items = ['Apple', 'Banana', 'Cherry']; return ( <MyList items={items} /> ); }
In the case of this example, the component MyList is expecting to receive an item prop that is an array of strings. The component App is passing a variety of items to the element
MyList, which in turn renders each item as a list item.
Props and state are both regular JavaScript objects in React. They do, however, have different roles. Here’s a side-by-side comparison of props vs state:
Props:
State:
function Counter(props) { const [count, setCount] = useState(0); const handleIncrement = () => { setCount(count + 1); }; const handleDecrement = () => { setCount(count - 1); It will return ( <div> <h1>Count: {count}</h1> <button onClick={handleIncrement}>+</button> <button onClick={handleDecrement}>-</button> </div> ); } function App() { return ( <div> <Counter initCount={5} /> </div> ); }
In this case, the Counter component will return an internal state variable, count, which initializes to 0. Second, it will have two functions, handleIncrement and handleDecrement, that it uses to set up the count state as a function.
This “App” component renders the “Counter” component, passing in an initial count prop with a value of 5; this is ignored because the Counter component will manage its internal state.
Props are used for passing information from a parent into a child component. The state handles the local state of the element. Props are read-only, meaning the child element cannot change it; the state allows itself to be modified by the component.
Props are quite a powerful way to pass data between a parent and child component in React. It lets one create reusable, composable components that can easily be swapped with different data. Props are read-only and thus cannot be modified by the child, which aids in preserving the integrity of your app.
It also comes, in the box, with something called PropTypes, a feature of React that allows validating the props passed to a component. It is quite useful for catching bugs and guaranteeing the overall quality of an application.
Another concept in React, besides “props,” used in managing the internal state of a component is called “state.” The component itself can change this; however, it can also be passed down to sub-components as props. By knowing the differences and right usages of props and states, you can actually build really strong, flexible, maintainable and extendable applications with React.
React online training props have the same meaning as function arguments. In HTML, they’re called attributes.
Course Name | Date | Details |
---|---|---|
React JS Training Course Online | Class Starts on 28th December,2024 28th December SAT&SUN (Weekend Batch) | View Details |
edureka.co