Conditional rendering of react

Conditional rendering

introduction

We know that react is a JavaScript library for building user interfaces. You can use it to create components with their own states, and then build more complex UI components from these components. But in some cases, we need to
render different UIs according to different conditions to achieve different functions. React uses JSX to define UI components, but it does not directly support loops or conditional expressions. Even so, we can use conditional rendering to solve our problems.

Conditional rendering method in react

  • if...else
  • Use null to prevent rendering
  • Element variable
  • And operator &&
  • Ternary operator
  • Immediately called function expression (IIFE)
  • Subassembly
  • Higher order components (HOC)

if...else

function UserGreeting(props){
	return <h1>Welcome back!</h1>
}
function GusetGreeting(props){
	return <h1>Please sign up.</h1>
}
function Greeting(props){
	const isLoggedIn = props.isLoggedIn;
	if(isLoggedIn){
		return <UserGreeting />;
	}
	return <GusetGreeting />;
}

ReactDOM.render(
	<Greeting isLoggedIn={true} />,
	document.getElementById('condition')
)

In the above code, which of the above components will be displayed depends on whether the user is logged in

Use null to prevent rendering

In rare cases, you may want to hide the component even if it has been rendered by other components. To accomplish this, you can make the
render method directly return null without any rendering

In the following example, rendering <WarningBanner />will be based on warnthe value in prop , if warn
the value of is false, then the component will not render

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(state => ({
			showWarning:!state.showWarning
		}))
	}
	render(){
		return(
			<div>
				<WarningBanner warn={this.state.showWarning} />
				<button onClick={this.handleToggleClick}>
					{
						this.state.showWarning?'Hide':'Show'
					}
				</button>
			</div>
		)
	}
}

ReactDOM.render(<Page />,document.getElementById('warning'))

Element variable

You can use variables to store elements, it can help you conditionally render part of the component, and other rendering parts will not change because of this

In the following example, we create two function components, representing the login and logout button to create a co-worker named LoginControl
assemblies and state, it will be rendered based on the current state <LoginButton />or <LogoutButton>. At the same time, it will also
render the<Greeting />

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('login-btn'))

And operator &&

By wrapping the code in curly braces, you can embed any expression in JSX. This also includes the logical AND (&&)
operator in JavaScript . He can easily perform conditional rendering of elements.

function Mailbox(props){
	const unreadMessages = props.unreadMessages;
	return(
		<div>
			<h1>Hello!</h1>
			{
				unreadMessages.length>0&&
				<h2>you have {unreadMessages.length}unread messages</h2>
			}
		</div>
	)
}
const messages = ['React','Re:React','Re:Re:React'];
ReactDOM.render(
	<Mailbox unreadMessages={messages} />,
	document.getElementById('mail-box')
)

The reason for this is that in JavaScript, it true&&expressionalways returns expression
and false&&expressionalways returns false.

Therefore, if the condition is true, &&the element on the right will be rendered, if it is false, React will ignore and skip it.

Ternary operator

Another way to inline conditional rendering is to use the trinocular operator in JavaScriptcondition?true:false

The <LoginControl />assembly as to render

render(){
		const isLoggedIn = this.state.isLoggedIn;
		return(
			<div>
				<Greeting isLoggedIn={isLoggedIn} />
				{isLoggedIn?<LogoutButton onClick = {this.handleLogoutClick} />:<LoginButton onClick ={this.handleLoginClick} />}			
			</div>
		)
	}

Immediately called function expression (IIFE)

Immediately execute the function as shown in the following code

(function myFunction(/*arguments*/){})(/*arguments*/)

When you are stuck in JSX code and want to write a large block of logic, you can use IIFE in addition to going back to the top

function render(){
	return(
		<div>
			{
				(() =>{
					if(renderComponent1){
						return <Component1 />
					}else{
						return <div />
					}
				})()
			}
		</div>
	)
}

Subassembly

This is a variant of IIFE, which is to replace this bit of immediate execution function with a normal function:

function render(){
	return(
		<div>
			<SubRender />
		</div>
	)
}
function SubRender(){
	if(renderComponent1){
		return <Component1 />
	}else{
		return <div />
	}
}

Higher-order components

Higher-order components are functions that return a new component and receive a component as a parameter.

Then we can write conditional statements in higher-order components and return different components

function highrOrderComponent(component){
	return function EnhancedComponent(props){
		if(condition){
			return <AnotherComponent {...props} />
		}
		return <Component {...props} />
	}
}

Guess you like

Origin www.cnblogs.com/dehenliu/p/12674884.html