More React - Basic Structure & Props

Daily Standup

Today I continued learning React in the class I’m doing. We’re using create-react-app and I’m definitely feeling like a lot of the basics are being abstracted away, but I’ll go with it for now. Actually, it’s a lot of new ideas even with a lot of things that have been taken away, so maybe it’s a good introduction. We started by building a basic app and passing props around.

Basic App Structure

Based on what we’ve covered so far, the basic structure of an app is as follows:

  • index.js uses React and ReactDOM to render your app file
  • The app file is itself a component which passes props on to its subcomponents. For example in our RecipeApp.js, we display the Recipe component and put several details in:
class RecipeApp extends Component {
render() {
return (
<div className="App">
<Recipe
title="Gnocchi"
ingredients={["Flour", "Potato", "Water", "Salt"]}
img="https://d3cizcpymoenau.cloudfront.net/images/legacy/33593/CVR_SFS_potato_gnocchi_008.jpg"
instructions="Blend all ingredients well. Form into small balls. Boil then pan-fry the balls."
/>
</div>
);
}
}
  • The Recipe component uses these props to render data:
class Recipe extends Component {
render() {
const {title, img, instructions} = this.props;
const ingredients = this.props.ingredients.map((ingredient, index) => (
<li key={index}>{ingredient}</li>
));
return (
<div className="recipe-card">
<div className="recipe-card-img">
<img src={img} alt={title} />
</div>
<div className="recipe-card-content">
<h2 className="recipe-card-title">{title} Recipe</h2>
<h3>Ingredients:</h3>
<ul>
{ingredients}
</ul>
<h3>Instructions:</h3>
<p>{instructions}</p>
</div>
</div>
)
}
}
  • Everything is linked using import statements, for example:
import React, { Component } from "react";
import Recipe from "./Recipe";
import "./RecipeApp.css";

defaultProps

The above example is very prescriptive but doesn’t handle optional data…but we can fix this!

class IngredientList extends Component {
static defaultProps = {
ingredients: []
};

Setting default props ensures that something is available for the .map() function above. Another option is to define the default props separately from the class:

class IngredientList extends Component {
render() {
return (
<ul>
{this.props.ingredients.map((ing, index) => (
<li key={index}>{ing}</li>
))}
</ul>
);
}
}

IngredientList.defaultProps = {
ingredients: []
};

propTypes

propTypes is a React package that sets requirements on component props. It’s not included in React and needs to be added separately: npm i prop-types. It’s only useful in development and does nothing in production. Here’s the documentation for future reference.

Up Next

More React lessons!