Created
January 23, 2018 12:21
-
-
Save onzag/a3f1da8ce8a549c4af2bb0651c64d7da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//OK so I will show here some of the basic shortcuts that are used within the templates | |
//First off we have the basic ternary operator | |
let something = <div>{this.props.user.name ? <span>{this.props.user.name}</span> : <span>No user name</span>}</div> | |
//it is a shorcut to: | |
let something; | |
if (this.props.user.name){ | |
something = <div><span>{this.props.user.name}</span></div> | |
} else { | |
something = <div><span>No user name</span></div> | |
} | |
//The second is the template string form eg. | |
let something = <div className={`something something--${this.props.user.type} something--cool`}></div> | |
//This is the equivalent of: | |
let something = <div className={"something something--" + this.props.user.type + " something--cool"}></div> | |
//Note that any expression can go in | |
let something = <div className={`something something--${this.props.user.type === 1 ? "nice" : "not-nice"} something--cool`}></div> | |
//Some other basic boolean operations are | |
let something = <span>{this.props.user.nickName || this.props.user.name || "default name"}</span> | |
//That basically represents, use the first one, or the second one or the thrid one | |
//The first one defined will take the value this is taking advantage of the cheap javascript evaluation mechanism | |
let value = this.props.user.nickName; | |
if (!value){ | |
value = this.props.user.name | |
} | |
if (!value){ | |
value = "default name" | |
} | |
let something = <span>{value}</span> | |
//And the last one trick used is using the and operator in order to make a cheap ternary operator | |
let something = <div>{this.props.user && <span>{this.props.user.name} - {this.props.user.type}</span>}</div> | |
//This basically makes it so that it doesn't create the second value unless there's an user | |
//this is the equivalent of | |
let something = <div></div> | |
if (this.props.user){ | |
something = <div><span>{this.props.user.name} - {this.props.user.type}</span></div> | |
} | |
//The reason for that is that it will evaluate the first and unlike the || operator it will only continue if it is defined | |
//so if the user is undefined the expression stops there and returns undefined, but if the expression has a value | |
//then it goes and executes the next code, and because there's no next code to execute it returns the last value | |
//this is very cheap and efficient similar to | |
let something = <div>{this.props.user ? <span>{this.props.user.name} - {this.props.user.type}</span> : null}</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment