ceckenrode ceckenrode - 3 months ago 66
React JSX Question

What is the equivalent to ng-if in react.js?

I'm coming to react from using angular and I'm trying to figure out a good react alternative to angular's ng-if directive where I render or dont render an element based on a condition. Take this code for example. I'm using typescript (tsx) btw but that shouldn't matter much.

"use strict";

import * as React from 'react';

interface MyProps {showMe: Boolean}
interface MyState {}

class Button extends React.Component <MyProps, MyState>{
constructor(props){
super(props);
this.state = {};
}

render(){
let button;
if (this.props.showMe === true){
button = (
<button type="submit" className="btn nav-btn-red">SIGN UP</button>
)
} else {
button = null;
}
return button;

}
}
export default Button;


This solution works, but is there another way that's generally used to achieve this effect? I'm just sort of guessing

Answer

How about ternary operator?

render() {
  return (
    this.props.showMe === true ? <button type="submit" className="btn nav-btn-red">SIGN UP</button> : null
  );
}