Getting Started with React: Lesson 9 of 14

Passing Props Through Children

Up Next

Conditionally Displaying Components

Autoplaying in 7 seconds!


This one will be really easy. We need to be able to click one of the dates being shown and have the index of that list item saved in the state of our App. This is going to be just like the ZipForm. The biggest difference is that we have to pass a function down from App, through WeatherList, and use it in WeatherListItem.

Let's start by adding a method to the App component that will be passed an index and will save that index as selectedDate on our component.

onDayClicked(dayIndex) {
  this.setState({ selectedDate: dayIndex });

Pretty simple. Nothing crazy here. Since we know this will be called later in reaction to a click, we need to bind this in the constructor.

Table of Contents

    this.onDayClicked = this.onDayClicked.bind(this);

    Then we need to pass it as a prop to our WeatherList.

    <WeatherList days={dates} onDayClicked={this.onDayClicked} />

    Now let's move on to our WeatherList. We need to pull this out of the props and pass it down to each WeatherListItem component through props. We also need to pass down the index that each WeatherListItem is in the array. We will need this when the item is clicked on. We can get this directly from the map function call.

    const { days, onDayClicked } = this.props;
    return (
      <div className="weather-list flex-parent">
        {, index) =>

    Almost done! We need to make a method in WeatherListItem that will be called on click and will then call our onDayClicked function.

    onClick() {
      const { onDayClicked, index } = this.props

    Don't forget to make a contructor and bind this to the onClick method.

    constructor(props) {
      this.onClick = this.onClick.bind(this);

    Lastly, we need to make sure this method gets called when an item is clicked on.

    return (
      <div className="weather-list-item" onClick={this.onClick}>
        <h1>{date.getMonth() + 1} / {date.getDate()}</h1>
        <h2>{day.temp.min.toFixed(1)}&deg;F &#124; {day.temp.max.toFixed(1)}&deg;F</h2>

    Now go to the browser, and try it out! Put in a zipcode and then click on one of the dates that pops up. If you view the App state in the React Dev Tools, you will see that the selectedDate piece of state is updated whenever you click on one of the days.

    This isn't very exciting to look at though. In the next one, we will finish up the application by showing more data about the day clicked on when one has been clicked on.

    Alex Sears

    2 posts

    Developing is not only my job but also my passion. I love to teach myself new things as much as I love teaching others. The more people we get involved in this little thing we call "web development," the better we can make it. I mean, we always need more cat videos, right?