React can render only part of the content in the corresponding state based on the application state.
If statement
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 <UserGreeting />;
}
return <GuestGreeting />;
}
ReactDOM.render(
// Try changing to isLoggedIn={true}:
<Greeting isLoggedIn={false} />.document.getElementById("root"));Copy the code
The and operator &&
Because in JavaScript, true && expression always returns expression, and false && expression always returns 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.
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 && (
<h2>You have {unreadMessages.length} unread messages.</h2>
)}
</div>
);
}
Copy the code
Ternary operator
condition ? True, false.
render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn
? <LogoutButton onClick={this.handleLogoutClick} />
: <LoginButton onClick={this.handleLoginClick} />
}
</div>
);
}
Copy the code
But it is not suitable for nesting overly complex cases. If the conditions are too complex, you should consider how to extract the components.
Preventing component rendering
You want to hide a component even if it has been rendered by another component. To do this, you can have the Render method return NULL directly without doing any rendering.
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("root"));
Copy the code
Returning NULL in the render method of a component does not affect the lifecycle of the component. For example, in the example above, componentDidUpdate is still called.