React: "Prop or nothing" in component property

kondziorf

In Firefly example project there is this defaultValue line in PostForm component:

<Input
  type="text"
  name="title"
  defaultValue={this.props.post.title || ''}
  required
/>

I got an error while rendering this component when parent component isn't passing any prop

TypeError: Cannot read property 'title' of undefined

When another component pass post prop it is fine. Why

|| ''

doesn't work for situation without prop passing?

Tholle

That's because post is undefined if your don't pass it as a prop, which will give rise to your error when you do this.props.post.title.

You need to check that post exists in the props as well:

<Input
  type="text"
  name="title"
  defaultValue={this.props.post && this.props.post.title || ''}
  required
/>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Property for react component is not defined

React: Updating Component Property

react await on component property

Passing array to component property in React

What is the 'prototype' property of a React component?

React functional component static property

Accessing key property of React component

Passing Property To Another Component - React

How to pass a property into a React function component?

Function as property in React.js + TypeScript component

Default property value in React component using TypeScript

Pasing objects as component property in React JSX

Passing property as pros in react functional component

React cannot read property 'map' of undefined on component

Use more than one property in React Component

How is it that my React component understands the 'children' property?

React Typescript: exclude property in higher order component

"Cannot read property 'onClick' of undefined" in React component

How to change property of Instantiated component in react?

Typescript React: Access component property types

React styled component as a property TypeScript issue

Is it ok to have own property in react component?

How to set conditional property on component in react

How to change react component's child property

react component error Cannot read property of undefined

TypeError: Cannot read property of null in React Component

Cannot read property from props in react component

Access 'name' property on React Dropzone component

How to add a Height property to a custom React Component