Last active
January 20, 2020 11:17
-
-
Save khusamov/aaf093a979980b6506fe4e2e49d1840b to your computer and use it in GitHub Desktop.
Условный рендеринг для функциональных компонент
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Mailbox(props) { | |
const unreadMessages = props.unreadMessages; | |
return ( | |
<div> | |
<h1>Здравствуйте!</h1> | |
{renderIf(unreadMessages.length > 0, ( | |
<h2> | |
У вас {unreadMessages.length} непрочитанных сообщений. | |
</h2> | |
)} | |
</div> | |
); | |
} | |
const messages = ['React', 'Re: React', 'Re:Re: React']; | |
ReactDOM.render( | |
<Mailbox unreadMessages={messages} />, | |
document.getElementById('root') | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {ReactElement} from 'react'; | |
/** | |
* Условный рендеринг для функциональных компонент. | |
* В функциональных компонентах не прокатывает паттерн условного рендеринга с применением логического оператора &&, | |
* потому что в типизации описано, что функциональный компонент может возвращать ReactElement или null, | |
* а логические значения возвращать нельзя. | |
* @link https://ru.reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator | |
* @param condition | |
* @param children | |
*/ | |
export default function renderIf(condition: boolean | Array<any>, children: ReactElement): ReactElement | null { | |
return (Array.isArray(condition) ? condition.length > 0 : condition) ? children : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment