Use defaultProps to give props a default value
Use propTypes to specify what props a component is expecting
Default values for props in a component
class IngredientList extends Component {
static defaultProps = {
ingredients: []
}
render() {
return (
<ul>
{this.props.ingredients.map((ing, index) => (
<li key={index}>{ing}</li>
))}
</ul>
);
}
}
This syntax also works
class IngredientList extends Component {
render() {
return (
<ul>
{this.props.ingredients.map((ing, index) => (
<li key={index}>{ing}</li>
))}
</ul>
);
}
}
IngredientList.defaultProps = {
ingredients: []
};
class App extends Component {
static defaultProps = {
recipes: [{
title: "Spaghetti",
ingredients: ["flour", "water"],
instructions: "Mix ingredients",
img: "spaghetti.jpg"
}]
}
render() {
return (
<div>
{this.props.recipes.map((r, index) => (
<Recipe key={index} title={r.title}
ingredients={r.ingredients}
img={r.img} instructions={r.instructions}
/>
))}
</div>
);
}
}
class App extends Component {
static defaultProps = {
recipes: [{
title: "Spaghetti",
ingredients: ["flour", "water"],
instructions: "Mix ingredients",
img: "spaghetti.jpg"
}]
}
render() {
return (
<div>
{this.props.recipes.map((r, index) => (
<Recipe key={index} {...r} />
))}
</div>
);
}
}
Development time type checker for your props
npm install --save prop-types
import PropTypes from 'prop-types';
class IngredientList extends Component {
static propTypes = {
ingredients: PropTypes.arrayOf(PropTypes.string)
.isRequired
}
render() {
return (
<ul>
{this.props.ingredients.map((ing, index) => (
<li key={index}>{ing}</li>
))}
</ul>
);
}
}