Home > front end >  Changing variable value throughout component when undefined
Changing variable value throughout component when undefined

Time:04-12

How can i change a variable that is used all throughout a component when it is undefined? For example:

<div>
 <div>{user.name}<div>
 <div>{user.id}<div>
<div>

If the state of the user is undefined how can i put another variable in it's place in both(or many) divs?

CodePudding user response:

So you want to conditionally check if your user object contains valid data; a very common situation which can be resolved with an if check.

Professionally I like to use the nullish coalescing operator, which, as per MDN:

returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

In your code, you would use it like this:

{user.name ?? fallbackVariable}

CodePudding user response:

Create a variable and then use that where ever you want in the component like below

const userObj = user ?? diffUser

<div>
 <div>{userObj?.name}<div>
 <div>{userObj?.id}<div>
<div>
  • Related