Conditional rendering in React based on if the variable is defined or not

Here we have used conditional rendering to prevent our code from breaking if the my_object variable is undefined.

import React from "react"

function MyComponent() {
    ...

    // Note the ? operator, it tells that property may or may not be present.
    let my_object = somethinghere.somechild?.moredeeper?.evenmoredeep

    return (
        <div>
            {
                my_object && (
                    <div>{my_object}</div>
                )
            }
        </div>
    )
}

export default MyComponent

the above code works, because in JS, true && expression always evaluates to expression, and false && expression always evaluates to false.

Resources:

https://reactjs.org/docs/conditional-rendering.html https://blog.logrocket.com/conditional-rendering-in-react-c6b0e5af381e/