Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

reactjs

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

like image 565
ceckenrode Avatar asked Apr 21 '16 13:04

ceckenrode


People also ask

Can I use if else in react JS?

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.

How do you use NG if?

Definition and UsageThe ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.

What is equivalent of document getElementById in React?

The equivalent of document. getElementById in React is refs. We can assign a ref to an element and then retrieve the element that's assigned the ref from the ref's current property. to create a ref with the useRef hook and assign it to myContainer .

Can you use plain JavaScript in React?

Unlike JavaScript, React does not allow you to use event names as you do with JavaScript, like onclick() ; hence you need to follow the event name as onClick() . You can still use plain JavaScript events using the window object used to represent the DOM document opened in the current browser window.


1 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>   ); } 
like image 156
Yuya Avatar answered Sep 22 '22 13:09

Yuya