How can I get default value

React is really a little difficult for me, I really need help, I wonder how I can get the default value excluding the way below. I tried {props.items.default} and {props.default}, neither of them worked. it’s not the point the challenge care about, I’m just curious about this and want to know more about React, thanks!

The code editor shows a ShoppingCart component. Define default props on this component which specify a prop items with a value of 0 .

  **Your code so far**

const ShoppingCart = (props) => {
return (
    <h1>Shopping Cart: {props.items}</h1>
// Change code below this line
ShoppingCart.defaultProps = {items: 0}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Use Default Props

Link to the challenge:

HI @RaymondGuo !

Are you looking to create a default value without using defaultProps?

If so, then you could create a fallback value right in the ShoppingCart component.

const ShoppingCart = (props) => {
  return (
      <h1>Shopping Cart: {props.items || 0}</h1>

When I use that component, I can provide a value like this.

 <ShoppingCart items="17" />

or choose not to pass in props and the fallback value I set will be used instead.

Here is an example showing both ways and you can see the two results rendered to the screen.

Hope that helps!

1 Like

Thanks, I got what you mean now, maybe I mixed the way of getting default value in component and object. In an object, we get a default value through"Object.default" method or some other way like this, but we can’t get a default value through the same way, right? I used console.log(props.items.default), it turns out undefined. I hope I made me clear, thanks!

For the challenge, you could write


and you will see the result of 0 in the console.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.