React conditional rendering
In React
can create different components to encapsulate the various behaviors you need. You can then render only some of them according to the state changes of the application.
React
the conditional rendering in is consistent with that in JavaScript, using the JavaScript operator if
or conditional operator to create an element that represents the current state, and then let React
update them according to them UI
.
Let’s take a look at two components:
function UserGreeting(props) {
return <h1>Welcome back!</h1>;
}
function GuestGreeting(props) {
return <h1>Please register first.</h1>;
}
We will create a Greeting
component, which displays one of them based on whether the user is logged in:
React instance
functionGreeting(props){constisLoggedIn=props.isLoggedIn;if(isLoggedIn){return<UserGreeting/>;}return<GuestGreeting/>;}ReactDOM.render(//Attempt to modify
isLoggedIn={true}:<GreetingisLoggedIn={false}/>,document.getElementById('example'));
Element variable
You can use variables to store elements. It can help you conditionally render part of the component, while the rest of the output will not be changed.
In the following example, we are going to create a file named LoginControl
the stateful components of the
It will render according to its current state <LoginButton/>
or <LogoutButton/>
which will also render the <Greeting/>
.
React instance
classLoginControlextendsReact.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(){constisLoggedIn=this.state.isLoggedIn;letbutton=null;if(isLoggedIn){button=
<LogoutButtononClick={this.handleLogoutClick}/>;}else{button=
<LoginButtononClick={this.handleLoginClick}/>;}return(<div>
<GreetingisLoggedIn={isLoggedIn}/>{button}</div>);}}ReactDOM.render(<LoginControl/>,document.getElementById('example'));
And operator &&
You can embed any expression in JSX by wrapping the code in curly braces, including JavaScript’s logic and &&
which can easily conditionally render an element
React instance
functionMailbox(props){constunreadMessages=props.unreadMessages;return(<div>
<h1>Hello!</h1>{unreadMessages.length>0&& <h2>
You have {unreadMessages.length} unread messages.
</h2>}</div>);}constmessages=['React','Re: React','Re:Re:
React'];ReactDOM.render(<MailboxunreadMessages={messages}/>,document.getElementById('example'));
In JavaScript true && expression
always return. expression
, and false && expression
always return. false
.
Therefore, if the condition is true
, the element to the right of &&
will be rendered; if it is false
, React
will ignore and skip it.
Ternary operator
Another method of conditional rendering is to use the conditional operator of JavaScript:
condition ? true : false。
In the following example, we use it to conditionally render a small piece oftext. render() { const isLoggedIn = this.state.isLoggedIn; return ( The user is {isLoggedIn ? 'currently' : 'not'} logged in. ); }
it can also be used in larger expressions, although not very intuitive:
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
Prevent components from rendering
In rare cases, you may want to hide the component, even if it is rendered byother components. Let render
method returns null
instead of its rendering results can be achieved.
In the following example <WarningBanner/>
according to attribut warn
conditional rendering of the value of the If warn
the value of``false`` the component does not render:
React instance
functionWarningBanner(props){if(!props.warn){returnnull;}return(<divclassName="warning">
warn!
</div>);}classPageextendsReact.Component{constructor(props){super(props);this.state={showWarning:true}this.handleToggleClick=this.handleToggleClick.bind(this);}handleToggleClick(){this.setState(prevState=>({showWarning:
!prevState.showWarning}));}render(){return(<div>
<WarningBannerwarn={this.state.showWarning}/>
<buttononClick={this.handleToggleClick}>{this.state.showWarning?'hide':'display'}</button>
</div>);}}ReactDOM.render(<Page/>,document.getElementById('example'));
Component render
method returns null
does not affect the callback of the component’s lifecycle method. For example, componentWillUpdate
and componentDidUpdate
it can still be called.