2018-09-30 23:01:58 +01:00
---
id: 5a24c314108439a4d403616b
title: Use Default Props
challengeType: 6
2019-08-05 09:17:33 -07:00
forumTopicId: 301418
2021-01-13 03:31:00 +01:00
dashedName: use-default-props
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
React also has an option to set default props. You can assign default props to a component as a property on the component itself and React assigns the default prop if necessary. This allows you to specify what a prop value should be if no value is explicitly provided. For example, if you declare `MyComponent.defaultProps = { location: 'San Francisco' }` , you have defined a location prop that's set to the string `San Francisco` , unless you specify otherwise. React assigns default props if props are undefined, but if you pass `null` as the value for a prop, it will remain `null` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
The code editor shows a `ShoppingCart` component. Define default props on this component which specify a prop `items` with a value of `0` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
The `ShoppingCart` component should render.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(
(function () {
const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart));
return mockedComponent.find('ShoppingCart').length === 1;
})()
);
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
The `ShoppingCart` component should have a default prop of `{ items: 0 }` .
```js
assert(
(function () {
const mockedComponent = Enzyme.mount(React.createElement(ShoppingCart));
mockedComponent.setProps({ items: undefined });
return mockedComponent.find('ShoppingCart').props().items === 0;
})()
);
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
## --after-user-code--
2018-09-30 23:01:58 +01:00
2020-07-13 18:58:50 +02:00
```jsx
2018-10-20 21:02:47 +03:00
ReactDOM.render(< ShoppingCart / > , document.getElementById('root'))
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
## --seed-contents--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```jsx
const ShoppingCart = (props) => {
return (
< div >
< h1 > Shopping Cart Component< / h1 >
< / div >
)
};
// Change code below this line
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
2020-07-13 18:58:50 +02:00
```jsx
2018-09-30 23:01:58 +01:00
const ShoppingCart = (props) => {
return (
< div >
< h1 > Shopping Cart Component< / h1 >
< / div >
)
};
2020-09-15 09:53:25 -07:00
// Change code below this line
2018-09-30 23:01:58 +01:00
ShoppingCart.defaultProps = {
items: 0
}
```