i create a use state in my react component like that:
const [loading, setLoading] = React.useState(false);
and in one project in return of component i saw something like this
<ListItemButton sx={{ color: `${loading && 'yellow'}` }}>
I can't find how that `${x && 'x' }`
syntax works
Can someone explain to me or show me the documentation of this?
CodePudding user response:
In this case `${loading && 'yellow'}`
is the same as loading && 'yellow'
Strings surrounded in backticks `
are called template literals. It allows you tu put variables in strings.
`I'm ${name}. I'm ${age} years old.`
&&
operators just means 'take the first falsey element and return it. If no falsey element is found, returns the last one.
0 && "" && "Banana"
will return 0
"Banana" && "" && 0
will return ""
"Banana" && 1 && 2
will return 2
CodePudding user response:
It's logical AND ( && ) operator, and next thing will execute incase if true
condition
let yellow = true;
console.log( yellow && "Yellow color" )
let blue = false;
console.log( blue && "Blue color" )
CodePudding user response:
Just simple plane javascript template literals
`${loading && 'yellow'}`
Will become
'yellow'
or
''
Depending on loading