DEV Community 👩‍💻👨‍💻

𝐃𝐚𝐧𝐫𝐞𝐳
𝐃𝐚𝐧𝐫𝐞𝐳

Posted on

Understanding React Props

Functional components can accept arguments, similar to JavaScript functions. These arguments are called props, and represent an object.

For example, we can use props in our Hello component:

function Hello(props) {
  return <p>Hello, {<u>props</u>.name}!</p>
}
Enter fullscreen mode Exit fullscreen mode

Now, we can add a name attribute to our element:

const el = <Hello name="David" />;
Enter fullscreen mode Exit fullscreen mode

The attribute value will be passed to the component when rendered.

An element can have multiple custom attributes, which will be passed to the component using the props object. You can use any custom names for your attributes.

Components using Components

Components can use other components to generate an output.

For example:

function App() {
  return <div>
    <Hello name="David" />
    <Hello name="James" />
    <Hello name="Amy" />
   </div>:
}
Enter fullscreen mode Exit fullscreen mode

Here, our App component uses the Hello component three times, each time with a new name attribute.

Generally, it is a good practice to split complex components into multiple smaller components, that are reusable.

Props in Class Components

Props can be accessed in class components using this.props.

For example:

class Hello extends React.Component {
  render() {
     return <p>Hello, {this.<u>props</u>.name}!</P>;
 }
}

Enter fullscreen mode Exit fullscreen mode

An important thing to consider is that props are read-only, meaning components cannot modify their props.

An Example

Now that we know how to create components and pass the data, let's create a shopping list.

Each item in our list will have a name and a price.

For example:

<Item name="Cheese" price="9.87" />
Enter fullscreen mode Exit fullscreen mode

The Item component will render a simple div element with the data:

function Item(props) {
  return <div className="item">
   <b>Name:</b> {props.name} <br />
   <b>Price:</b> {props.price}
   </div>;
}
Enter fullscreen mode Exit fullscreen mode

Now we can use our component and create multiple items for our shopping list:

<Item name="Cheese" price="9.87" />
<Item name="Bread" price="2.5" />
<Item name="Ice cream" price="24" />
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.