Skip to content

Instantly share code, notes, and snippets.

@tanayv
Last active September 10, 2018 01:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanayv/76c89cbfe509c99c722f5e86a5a11f62 to your computer and use it in GitHub Desktop.
Save tanayv/76c89cbfe509c99c722f5e86a5a11f62 to your computer and use it in GitHub Desktop.
Conditional Rendering: Angular & React
/* How I would do it in Angular (For example in x.component.html) */
<div class="nav">
<div class="option" *ngClass={'selected': 'activeView == 0'} (click)="setView(0)">Playback</div>
<div class="option" *ngClass={'selected': 'activeView == 1'} (click)="setView(1)">Lyrics</div>
<div class="option" *ngClass={'selected': 'activeView == 2'} (click)="setView(2)">Translation</div>
</div>
/* How I did it in react */
class Nav extends Component {
render() {
return (
<div className="nav">
<div onClick={() => this.setNavView(0)} className={ngClass("option", "selected", this.props.activeView, 0)}>Playback</div>
<div onClick={() => this.setNavView(1)} className={ngClass("option", "selected", this.props.activeView, 1)}>Lyrics</div>
<div onClick={() => this.setNavView(2)} className={ngClass("option", "selected", this.props.activeView, 2)}>Translation</div>
</div>
)
}
}
/**
* Adds a class to the element when the element's index matches the active index
* @param {string} baseValue The class that each element should have
* @param {string} concatValue The class that only the selected element should have
* @param {number} targetView The index of the selected value
* @param {number} activeView The index of the element passed to the function
*/
const ngClass = (baseValue, concatValue, targetView, activeView) => {
if (activeView === targetView)
return baseValue + " " + concatValue;
else
return baseValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment