Computer scienceFrontendReactReact Components

Properties

13 minutes read

In React, props (which stands for "properties"), provide a way for you to pass data from a parent component to its child components. These props are read-only; they can't be changed by the child components. You use them to tailor and set up child components based on the parent component's requirements. Although props might seem like HTML attributes, they can convey various JavaScript values. These values could be objects, arrays, functions, and even other components. In this topic, you'll learn about React properties, how to use them, and see examples you can try yourself.

Properties you might be familiar with

Properties (props) are bits of information that you pass to a component. The HTML properties that you're already familiar with are also used as React properties, but with some minor name alterations. For instance, properties like className, src, alt, width, and height can all be passed as props to an <img>:

function Picture() {
  return (
    <img
      className="picture"
      src="https://example-img"
      alt="Example img"
      width={100}
      height={100}
    />
  );
}

export default Picture;

The props img tag uses are predefined. However, you're free to pass any props you want to your custom components in order to personalize them or make them unique. Let's find out how this is done!

Pass props from parent to child component

In the parent component, specify the props you want to pass. Say, you have a User parent component, and you wish to relay props to a child component, you can do it this way:

function User() {
  const age = 25;
  const city = "New York";

  return (
    <Profile
      fullName={{ name: 'John', surname: 'Doe' }}
      age={age}
      city={city}
    />
  );
}

The Profile component takes in three props:

  • The fullName prop is an object containing properties name and surname. It gets passed as an object literal using double curly braces: {{ name: 'John', surname: 'Doe' }}.

  • The age and city props get passed along with their respective values, like this: age={age}.

This code shows how you can use props to customize the Profile component within the User component. The transferred props can now be used inside the Profile component.

Utilizing properties within the child component

Within the child component, the props object is used to access properties. As an example, consider the Profile component where you may access these properties like this:

function Profile(props) {
  return (
    <div>
      <h2>Name: {props.fullName.name} {props.fullName.surname}</h2>
      <p>Age: {props.age}</p>
      <p>City: {props.city}</p>
    </div>
  );
}

This would be the result:

Result of using the passed props

You have another option, too; use destructuring to extract the prop value straight away:

function Profile({ fullName, age, city }) {
  return (
    <div>
      <h2>Name: {fullName.name} {fullName.surname}</h2>
      <p>Age: {age}</p>
      <p>City: {city}</p>
    </div>
  );
}

By destructuring, you access the individual props within the component directly, avoiding the need to reference props every time. This approach can make your code more concise and simpler to read. Remember that the { } pair in the Profile() function is integral for destructuring.

Destructuring also lets you define default prop values; in the Profile component, you can modify it like so:

function Profile({ fullName, age = 30, city = "Unknown" }) {
  return (
    <div>
      <h2>Name: {fullName.name} {fullName.surname}</h2>
      <p>Age: {age}</p>
      <p>City: {city}</p>
    </div>
  );
}

function User() {
  return (
    <Profile
      fullName={{ name: 'John', surname: 'Doe' }}
    />
  );
}

In this example, you assign default values directly within the function parameter using the = operator. So when you write age = 30 and city = "Unknown", you're setting default prop values for age and city. Note, however, that this example doesn't specify a default value for the fullName prop, meaning it's required when you use the Profile component.

The result would look like this:

Result of using default props

Forwarding props

When you need to pass multiple props to a child, you can forward props with the JSX spread syntax. This technique in React allows passing all props from a parent component to a child component without specifically mentioning each prop. It simplifies the prop passing process down the component hierarchy.

Let's look at an example to understand how to forward props using the JSX spread syntax:

function ParentComponent() {
  const commonProps = {
    prop1: "value1",
    prop2: "value2",
    prop3: "value3"
  };

  return (
    <ChildComponent {...commonProps} />
  );
}

function ChildComponent(props) {
  return (
    <div>
      <p>Prop 1: {props.prop1}</p>
      <p>Prop 2: {props.prop2}</p>
      <p>Prop 3: {props.prop3}</p>
    </div>
  );
}

By employing the JSX spread syntax ({...commonProps}), all the props within commonProps are passed to the ChildComponent. In the ChildComponent, you can access the received props as usual (props.prop1, props.prop2, props.prop3).

Forwarding props using the JSX spread syntax allows you to pass multiple props from a parent component to a child component efficiently and concisely. It helps cut down code duplication and simplifies the process of prop propagation.

While the JSX spread syntax is handy for forwarding props, don't overuse it. If you notice that you're using the spread syntax in almost all components, it might signal a design issue that needs attention. In such cases, it's advisable to consider breaking down your components and passing children as JSX instead. Rather than heavily relying on spreading props, you can craft more focused and reusable components that accept specific props and render their children directly.

Passing components as props

In React, passing components as props means you give a separate component as a prop to another component. This process enables dynamic composition and customization of components.

Using this method, you can generate a flexible card component for diverse scenarios:

function App() {
  return (
    <div>
      <Card
        body={<CardBody content="Body here" />}
        footer={<CardFooter content="Footer here" />}
        header={<CardHeader content="Header here" />}
      />
    </div>
  );
}

function Card({ body, footer, header }) {
  return (
    <div>
        {header}
        {body}
        {footer}
    </div>
  );
}

function CardBody({content}) {
  return (
    <div className="card">
      <p>{ content } </p>
    </div>
  );
}

function CardHeader({content}) {
  return (
    <div className="card">
      <h3>{content}</h3>
    </div>
  );
}

function CardFooter({content}) {
  return (
     <div className="card">
      <h4>{content}</h4>
    </div>
  );
}

By giving components as props, you as the parent component can control and tweak the behavior and appearance of the child component. Different components passed as props can facilitate various functions or visuals within the child component. This method promotes enhanced flexibility and reusability in developing React applications.

Here's the outcome:

Result of the card component

Passing jsx as children

When you pass JSX as children in React, you provide JSX elements or components as content within a parent component's opening and closing tags. This practice enables a more flexible and dynamic assembly of components.

Here is a sample to explain how to pass JSX as children:

function ParentComponent() {
  return (
    <div>
      <h2>Parent Component</h2>
      <ChildComponent>
        <p>This is JSX passed as a child.</p>
        <button>Click me</button>
      </ChildComponent>
    </div>
  );
}

function ChildComponent(props) {
  return (
    <div>
      <h3>Child Component</h3>
      {props.children}
    </div>
  );
}

In this example, the ParentComponent display the ChildComponent and offers JSX elements (<p>and <button>) as the children of ChildComponent. You place the JSX elements within the opening and closing tags of ChildComponent.

Within the ChildComponent, you can access the received children using the props.children property. Here, the children are displayed directly within the ChildComponent's JSX structure.

With JSX as children, you can create more adaptive and flexible components. This method helps compose intricate UI structures and customize a component's content according to specific requirements.

The immutable nature of props

In React, props are viewed as immutable. This means you can't change their values once they are set. Thanks to this, a one-way data flow is maintained and it ensures that components cannot directly alter the data they receive.

import React from 'react';

const MyComponent = (props) => {
  // Trying to change the prop value
  props.name = 'John'; // But this won't work

  return <div>Hello, {props.name}!</div>;
};

const App = () => {
  const name = 'Alice';

  return <MyComponent name={name} />;
};

export default App;

In this example, we have a MyComponent receiving a prop called name. Inside the component, we try to change the value of props.name by assigning it a new value, 'John'. But if you attempt to run this code, the prop's value won't change.

This situation happens because React treats props as read-only. If you need to change the value of a prop, you should manage it as state within the component - a topic you'll learn about later - or give a different prop value from the parent component.

By making sure props stay immutable, React ensures that components stay predictable and simpler to understand. This helps to avoid unexpected side effects and makes it easier to follow and comprehend your application's data flow.

Conclusion

To conclude, props in React are a crucial concept that lets you pass data from a parent component to its child components. They offer a method to dynamically customize and set up components. Props are useful for sending data and functionality down the component tree, which aids in building reusable and modular components. Giving props in React involves two steps: specifying the props in the parent component and then accessing them in the child component. You can give props by adding them as attributes when rendering a child component within the parent component. The child component can then access the given props through its props object.

10 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo