Conditional Rendering
-
Conditional rendering in React works the same way conditions work in JavaScript
Code Examples
-
function UserGreeting(props) { return <h1>Welcome back!</h1>; }
function GuestGreeting(props) { return <h1>Please sign up.</h1>; }
-
function Greeting(props) { const isLoggedIn = props.isLoggedIn; if (isLoggedIn) { return
; } return ; } ReactDOM.render( // Try changing to isLoggedIn={true}: <Greeting isLoggedIn={false} />, document.getElementById(‘root’) );
Element Variables
- used to store elements
-
Code Sample:
-
function LoginButton(props) { return ( <button onClick={props.onClick}> Login </button> ); }
function LogoutButton(props) { return ( <button onClick={props.onClick}> Logout </button> ); } -
class LoginControl extends React.Component { constructor(props) { super(props); this.handleLoginClick = this.handleLoginClick.bind(this); this.handleLogoutClick = this.handleLogoutClick.bind(this); this.state = {isLoggedIn: false}; }
handleLoginClick() { this.setState({isLoggedIn: true}); } handleLogoutClick() { this.setState({isLoggedIn: false}); } render() { const isLoggedIn = this.state.isLoggedIn; let button; if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> ); } } ReactDOM.render( <LoginControl />, document.getElementById('root') );
Preventing Component from Rendering
- used when you want to hide element even though it was rendered by another component
-
function WarningBanner(props) { if (!props.warn) { return null; }