September 30, 2022

Shartli ko'rsatish yoki rendering | Hooks qo'llanma 11

Turli shart va statelarga ko'ra turli UI larni ko'rsatish.

Reactda shartli ko'rsatish yordamida dinamik dasturlar yasashimiz qulay va oson. Shartli ko'rsatish bu biror shartga ko'ra turli UI element yoki componentlarni ko'rsatish.

CodeSandbox link

Bu darsdagi to'liq kodni quyidan topa olasiz: https://codesandbox.io/s/conditional-rendering-react-l578jj

Mantiqiy AND(Va) operatori

Mantiqiy AND(&&) operatori ba'zi shartlarga ko'ra turli UI larni ko'rsatish uchun ishlatilina oladi. Aytaylik biz biror xabar masalan "You have 1 new notification" ni xabar 1ta yoki undan ko'p bo'lsa ko'rsatamiz. Birinchi navbatda NotificationCard componentini yaratamiz. Bu oddiy local state ga bog'liq matn bo'ladi.

import React, { useState } from "react";

const NotificationCard = () => {
    const [notificationNumber, setNotificationNumber] = useState(1)

    return (
        <div>
            <p>You have {notificationNumber} new notification </p>
        </div>
    );
};

export default NotificationCard;

Keyin biz bu componentga mantiqiy AND(&&) operatorini ishlatib shart qo'shamiz. notificationNumber 1ga teng yoki katta bo'lsagina matnni ko'rsat degan.

<div>
  {notificationNumber >= 1 &&
    <p>You have {notificationNumber} new notification</p>}
</div>

notificationNumber boshlang'ich qiymatini 0ga o'zgartirib ko'ring va matn yo'qolganini ko'rasiz.

const [notificationNumber, setNotificationNumber] = useState(0)

If...else shartli operator

If...else operatori yordamida shartlarni belgilashimiz va uning true yoki false ekanligiga qarab biror narsa qilishimiz mumkin. Quyidagi misolda biz isLoggedIn ning qiymatiga qarab Logout yoki Login buttonlarini ko'rsatamiz.

import React, { useState } from "react";

const SignInButton = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(true);

    if (isLoggedIn) {
        return <button>Logout</button>;
    } else {
        // Agar foydalanuvchi ro'yxatdan o'tmagan bo'lsa
        return <button>Login</button>;
    }
};

export default SignInButton;

isLoggedIn ning boshlang'ich qiymatini falsega oz'gartirib ko'ring va Logout buttoni emas Login buttonini ko'ring.

const [isLoggedIn, setIsLoggedIn] = useState(false)
Eslatma: If...else shartli operatori faqat returnning tashqarisida ishlaydi. Return ning ichida esa ternary operatoridan foydalanamiz.

Ternary Operatoridan foydalanish

if...else statement ining muqobili bu ternary operatori hisoblanadi. Biz tepadagi kabi misoldan foydalanamiz, lekin bu safar ternary bilan shartli ko'rsatishni bajaramiz.

const SignInButton = () => {
    const [isLoggedIn, setIsLoggedIn] = useState(true);

    return (
        <div>
            {isLoggedIn ? <button>Logout</button> : <button>Login</button>}
        </div>
        );
}

export default SignInButton

Natija if...else bilan bir xil faqat kod toza va o'qishga juda oson.