The Importance of Props in React

amsfreeman

amsfreeman

Posted on July 27, 2023

The Importance of Props in React

In my software development bootcamp, we first learned Vanilla JS, before moving onto React. When learning React one of the first thing I encountered was passing props. Props? What were those? Here I will walk through what props are, and how to pass them.

Props is short for properties, and they allow one to pass information from a parent component to a child component. A parent component returns a child component. Props is the only way the child component can have access to data from the parent component. Props therefore is data passed from the parent to the child component, which allows the child component to make use of this data.

Additionally it is important to note, this props information flow can only go one way: Parent -> Child. Props cannot be passed like this: Parent <- Child. There is a way to pass information from a child component to a parent component, which is called reverse information flow, but unfortunately it is not as easy as props!

Now let's get into the passing of props.

Let's say we have a component called App, which is our top level component. In the below example, it has access to a books array, which was fetched from a localhost. App will then pass the books array to the child component BooksContainer within the return.

import {useState, useEffect} from React

function App() {
  const [booksArray, setBooksArray] = useState([])


  useEffect(() => {
    fetch('http://localhost:4000/books')
      .then(r => r.json())
      .then(allBooksArray => setBooksArray(allBooksArray))
  }, [])

  return (
    <div>
      <BookContainer booksArray={booksArray}/>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

Next our child component will accept the props. There are two ways to do this. The first way is that the child component can accept the props using the key word props. That would look like this:

function BookContainer(props)
Enter fullscreen mode Exit fullscreen mode

If props are accepted like this, props will need to accessed by typing props.(whatever) whenever they are used within this child component. Below is an example of using this syntax.

function BookContainer(props) {
  return (
    <div>
     {props.booksArray}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

This works perfectly well and maybe be easier to understand as one is getting started working with props.

Another way to handle receiving props on the child component side is to destructure props. In this case the child component still accepts the props, but instead a {} is added and the name of the props is used. Below is an example of this.

function BookContainer({booksArray}) {
  return (
    <div>
     {booksArray}
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

This way may look a bit confusing at first. The props keyword is gone! But ultimately, destructuring props makes our work in the child component easier (no typing props.(whatever)!) and it make the code look cleaner.

Okay, so now we have our BooksArray in our child component. Yay! But it is still just an array! How can we get access to what is in the array? We need to map through it, which was the topic of my last blog (When and how to use forEach and map in Vanilla JS vs React by Amelia Freeman).

After that, we will pass props to our next child component Book, and finally we will return our bookComponents.

We can do that as below:

function BookContainer({bookArray}) {
  const bookComponents = bookArray.map(book => {
    return (
      < Book
        key={book.id}
        id={book.id}
        title={book.title}
        author={book.notes}
        summary={book.summary}
      />
    )
  })
  return (
    <div>
      {bookComponents}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Let's break this down a bit.

In this line we are accepting our props. Note they are destructed, as we have ({bookArray}) and not (props).

The next line {}> starts our map. Here were a creating a variable bookComponents, which hold all our books. We are then mapping through the book array.

Then in the <{}> we doing our actual mapping.

We are saying in the case below, that for each book, we want to return a title, an author, and a summary. We will also need each book to have an id. Finally, each book must have a key, which is required by React as a unique identifier.

(book => {
    return (
      < Book
        key={book.id}
        id={book.id}
        title={book.title}
        author={book.notes}
        summary={book.summary}
      />
    )
  })
Enter fullscreen mode Exit fullscreen mode

Finally as mentioned above, the bookComponents are returned as so:

 return (
    <div>
      {bookComponents}
    </div>
  )
Enter fullscreen mode Exit fullscreen mode

Next, we can accept props in our child component Book. That looks like this:

function Book({title, author, summary}) {
  return (
    <div>
      <h3>{title} </h3>
      <h4>{author}</h4>
      <p>{summary}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Again, let's break this down. Our child component Book is accepting props, which here have been destructured into title, author, and summary. Finally, we are taking our props and returning them on our page. Title will be an

header, author and

header, and summary a

paragraph.

There are two slightly different ways to pass props from the parent component BookContainer to the child component Book, both of which are outlined below.

Alternate 1:
We could simply pass our whole book object from our parent component down to the Book component. We still do need to set the unique key here in the parent component BookContainer. If we wanted to do it this way, it would look like this:

function BookContainer({bookArray}) {
  const bookComponents = bookArray.map(book => {
    return (
      < Book
        key={book.id}
        book={book}
      />
    )
  })
  return (
    <div>
      {bookComponents}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

When our child component book accepts the props, we would then need to pull out what we need (id, title, author summary) on the other side, in the Book component.

That would look like this:

function Book({book}) {
const book = {title, author, summary}
  return (
    <div>
      <h3>{title} </h3>
      <h4>{author}</h4>
      <p>{summary}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Alternate 2:
The other thing is that we could use the props key word instead. We still do need to set the unique key here in the parent component BookContainer.

That would look like this in the parent component BookContainer:

function BookContainer({bookArray}) {
  const bookComponents = bookArray.map(book => {
    return (
      < Book
        key={book.id}
        book={book}
      />
    )
  })
  return (
    <div>
      {bookComponents}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

And like this in the child component book:

function Book(props) {
  return (
    <div>
      <h3>{props.title} </h3>
      <h4>{props.author}</p>
      <p>{props.summary}</p>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

As you can see passing props can be done a few different ways. Whichever way you understand best is a great way to start! As you continue to work in React and pass props, you will figure out which way works best for you!

Passing props is a vital piece to understand working in React. Only be understanding passing props, can we move onto reverse information flow and other more complicated aspects of React.

Hopefully this helps to give an introduction to props!

(Cross posted on Medium at: The Importance of Props in React).

đź’– đź’Ş đź™… đźš©
amsfreeman
amsfreeman

Posted on July 27, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related