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
if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction.
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.
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 .
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.
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> ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With