React conditional Rendering
In react, you can create different components to encapsulate various actions you need. Then, you can render only part of the application according to the state change.
Conditional rendering in react is the same as that in Javascript. Use the Javascript operator if or conditional operator to create elements that represent the current state, and then let react update the UI based on them.
Let's take a look at two components:
Function usergreeting (props) {return
We will create a greeting component, which will display one of them based on whether the user is logged on:
React instance
Function greeting (props ){
Const isloggedin = props. isloggedin;
If (isloggedin ){
Return <usergreeting/>;
}
Return <guestgreeting/>;
}
Reactdom. Render (
// Try to modify
Isloggedin = {true }: <greeting isloggedin = {false}/>, document. getelementbyid ('example ')
);
Element variable
You can use variables to store elements. It helps you to render a part of the component with conditions, while other parts of the output will not be changed.
In the following example, we will create a stateful component named logincontrol.
It renders <loginbutton/> or <logoutbutton/> Based on the current status. It also renders <greeting/> in the preceding example.
React instance
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 = null;
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(‘example‘)
);
And operators &&
You can embed any expression in jsx by wrapping the Code with curly brackets, including JavaScript logic and &, which can easily render an element by conditions.
React instance
Function mailbox (props ){
Const unreadmessages = props. unreadmessages;
Return (
<Div> );
}
Const messages = ['react ','re: React','re: Re: React '];
Reactdom. Render (<mailbox unreadmessages = {messages}/>,
Document. getelementbyid ('example ')
);
In JavaScript, true & Expression always returnsExpressionWhile false & Expression always returnsFalse.
Therefore, if the condition isTrue, & The elements on the right side will be rendered.False, React ignores and skips it.
Three-object Operator
Another method of conditional rendering is to use JavaScript conditional operators:
condition ? true : false。
In the following example, we use it for conditional rendering of a small piece of text.
render() {
const isLoggedIn = this.state.isLoggedIn; return ( The user is {isLoggedIn ? ‘currently‘ : ‘not‘} logged in. );
}
It can also be used in large expressions, although not intuitive:
render() { const isLoggedIn = this.state.isLoggedIn; return ( <div> {isLoggedIn ? ( <LogoutButton onClick={this.handleLogoutClick} /> ) : ( <LoginButton onClick={this.handleLoginClick} /> )} </div> );}
Block component Rendering
In rare cases, you may want to hide a component even if it is rendered by another component. Let the render method return NULL instead of its rendering result.
In the following example, <warningbanner/> is rendered based on the value of the attribute warn. If the value of warn is false, the component will not render:
React instance
Function warningbanner (props ){
If (! Props. Warn ){
Return NULL;
} Return (
<Div classname = "warning"> warning! </Div>
);
}
Class page extends react. 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> <warningbanner warn = {This. state. showwarning}/> <button onclick = {This. handletoggleclick}> {This. state. showwarning? 'Hiding ': 'display'} </button> </div>
);
}
}
Reactdom. Render (<page/>,
Document. getelementbyid ('example ')
);
If the component's render method returns NULL, the callback of the component's life cycle method is not affected. For example, componentwillupdate and componentdidupdate can still be called.
Frontend react conditional Rendering