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
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With