If not effectively used, ternary operators can make extra long and hard-to-read statements. Using ternary statements effectively is essential to writing clean and efficient code. Ternary operator and optional chaining are helpful when writing conditional rendering in JSX.
Below is a simple usage of an
interface SignupFormProps {
hasError: boolean
errorMessage: string
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
{props.hasError && props.errorMessage}
</>
)
}
My ternary
is equivalent to
if(props.hasError){
return props.errorMessage
}
interface SignupFormProps {
hasError: boolean
errorMessage: string
succesMessage: string
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
{props.hasError ? props.errorMessage : props.succesMessage}
</>
)
}
My ternary
is equivalent to
if(props.hasError){
return props.errorMessage
}
else {
return props.succesMessage
}
interface SignupFormProps {
mximumListSize?: number
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
{!!props.mximumListSize && props.mximumListSize > 10 && "Maximum list size exceeded"}
</>
)
}
The
Here is the standard if statement for the same.
if(props.mximumListSize !== undefined && props.mximumListSize > 10){
return "Maximum list size exceeded"
}
if(props.mximumListSize === undefined){
return false;
}
else {
return true;
}
Here I am trying to print the length and the first element of an optional array. Since the
interface SignupFormProps {
idList?: number[]
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
{props.idList?.length}
{props.idList?.[0]}
</>
)
}
Note that I use a question mark in the ternary.
That means checking for the array length if
Below is the standard
if(props.idList){
return props.idList.length
}
if(props.idList){
return props.idList[0]
}
Here I receive an optional function reference
interface SignupFormProps {
onInputClick?: () => null
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
<input type="text" onClick={() => props.onInputClick?.()}/>
</>
)
}
The optional chaining
if(props.onInputClick){
props.onInputClick?.()
}
In this example, I am dealing with an optional parameter
interface SignupFormProps {
contact?: Contact
}
interface Contact {
email?: string[]
}
export const SignupForm = (props: SignupFormProps) =>{
return(
<>
<input type="text" value={props.contact?.email?.[0]}/>
</>
)
}
There are two checks to this optional chaining.
The
Below is how I can achieve the same.
if(props.contact && props.contact.email){
return props.contact.email[0]
}