Answer a question

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

Answers

How about ternary operator?

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

You can also use &&:

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

Large block as in the comment can easily be handled by wrapping the JSX in ()s:

render() {
  return this.props.showMe && (
    <div className="container">
      <button type="submit" className="btn nav-btn-red">
        SIGN UP
      </button>
    </div>
  );
}

Also inline:

render() {
  return (
    <div className="container">
      {this.props.showMe && <button type="submit" className="btn nav-btn-red">SIGN UP</button>}
    </div>
  );
}
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐