Understanding React Props: A Comprehensive Guide

Last updated on Jul 16,2024 48 Views

Sunita Mallick
Experienced tech content writer passionate about creating clear and helpful content for... Experienced tech content writer passionate about creating clear and helpful content for learners. In my free time, I love exploring the latest technology.

React Prop

Table of Contents:

What are props in React?

 

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.

What are React PropTypes?

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.

 

Default Props and their Examples

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’. 

 

State and Props with Its examples

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.

 

What are the props of an object in React?

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.

 

What is props vs state?

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:

  • Props are used to transfer data from a parent component to a child component.
  • Props themselves are read-only, and the child cannot change them.
  • Props are provided to the child at the creation of that child.
  • Props can be of any data type, which indicates strings, numbers, booleans, arrays, objects, or even functions.

 

State:

  • The state is meant to handle a component’s private nuis_CONDITIONal information.
  • The state can change by itself.
  • The state would either be set up in the constructor or with the aid of the useState hook.
  • The state can be passed down to child components as props.

 

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.

 

Conclusion

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. 

Upcoming Batches For React JS Certification Course Online
Course NameDateDetails
React JS Certification Course Online

Class Starts on 20th July,2024

20th July

SAT&SUN (Weekend Batch)
View Details
React JS Certification Course Online

Class Starts on 21st September,2024

21st September

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Understanding React Props: A Comprehensive Guide

edureka.co