akaFinch
akaFinch

Reputation: 3

Undefined prop value in child component

I'm attempting to read an array item in a child component via props. Logging the array in the child component works. But if I try to access a property of one of the array items by indexing it with the :id from match.params, it tells me that I can't access a property of 'undefined'.

Any guidance would be greatly appreciated.

tours.js

import React, { Component } from "react";
import { Route, Switch } from "react-router-dom";

// Page Imports
import Summary from "../pages/summary";
import Details from "../pages/details";

// Component Imports
import Homebutton from "../components/homebutton";

class Tours extends Component {
  state = {
    tours: []
  };

  componentDidMount() {
    window.scrollTo(0, 0);
    fetch("/tours")
      .then(res => res.json())
      .then(res => this.setState({ tours: res }));
  }

  render() {
    const tours = this.state.tours;

    return (
      <section className="tours-page">
        <div className="center-box">
          <h2>Tours</h2>
        </div>
        <Switch>
          <Route
            exact
            path={this.props.match.url}
            render={props => <Summary {...props} tours={tours} />}
          />
          <Route
            path={this.props.match.url + "/:id"}
            render={props => <Details {...props} tours={tours} />}
          />
        </Switch>
        <Homebutton />
      </section>
    );
  }
}

export default Tours;

details.js

import React from "react";

const Details = ({
  tours,
  match: {
    params: { id }
  }
}) => (
  <section className="details">
    <h2>{tours[id]["name"]}</h2>
  </section>
);

export default Details;

Upvotes: 0

Views: 126

Answers (2)

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18113

To be sure that tours[id] is not undefined you should check it first

<section className="details">
 <h2>{tours[id] && tours[id]["name"]}</h2>
</section>

Upvotes: 1

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8102

As componentDidMountalways gets called after first render, you must validate your props to avoid app crashes:


const Details = ({
  tours,
  match: {
    params: { id }
  }
}) => (
  <section className="details">
    <h2>{tours.length && tours[id]["name"]}</h2>
  </section>
);

Upvotes: 0

Related Questions