Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for handling null prop when accessing prop attribute

I have a React component that I pass a prop that I use to set the initial state of the component as such:

class ContactForm extends React.Component {
  constructor(props) {
    super(props)

    const { contact } = this.props
    const { name, position, email, phone_number } = contact

    this.state = {
      name: name,
      position: position,
      email: email,
      phone_number: phone_number
    }
  }
}

However, the contact prop that I pass could possibly be null. What is the best way to handle a null prop when I am trying to access the prop attributes? I can have an if statement that checks whether or not contact is null, and set the state as such, like this:

if (contact) {
  const { name, position, email, phone_number } = contact

  this.state = {
    name: name,
    position: position,
    email: email,
    phone_number: phone_number
  }
} else {
  this.state = {
    name: '',
    position: '',
    email: '',
    phone_number: ''
  }
}

But I was wondering if there is a better approach

like image 351
Marcus Christiansen Avatar asked Jun 24 '18 16:06

Marcus Christiansen


1 Answers

You can default contact to an empty object, and give the other values empty strings as default:

class ContactForm extends React.Component {
  constructor(props) {
    super(props)
    // Only undefined values can be given default values when destructuring,
    // so it needs to be written like this
    const contact = this.props.contact || {}
    const { name = '', position = '', email = '', phone_number = '' } = contact

    this.state = {
      name,
      position,
      email,
      phone_number
    }
  }
}
like image 196
Tholle Avatar answered Sep 19 '22 14:09

Tholle