The optional chaining operator (?.
) in React TS is useful when working with potentially undefined or null values in order to prevent runtime errors.
Here's an example of when to use the optional chaining operator in React TS:
interface User { name: string; address?: { street: string; city: string; }; } function UserInfo({ user }: { user: User }) { return ( <div> <h2>{user.name}</h2> {user.address?.street && user.address?.city ? ( <p> {user.address.street}, {user.address.city} </p> ) : ( <p>No address available.</p> )} </div> ); }
In this example, we have a User
interface with an optional address
field. In the UserInfo
component, we're rendering the user's name and address (if available).
To prevent runtime errors when accessing user.address.street
and user.address.city
, we use the optional chaining operator (?.
) to check if user.address
is truthy before trying to access its properties.
If user.address
is undefined or null, the expression user.address?.street
and user.address?.city
will return undefined and the conditional rendering will render the "No address available." message.
This way, we can safely render the user's information without worrying about runtime errors due to undefined or null values.
No comments:
Post a Comment