React shartli render qilish


React-da siz componentlarni shartli ravishda ko‘rsatishingiz mumkin.

Buning uchun bir necha usullar mavjud.


ULASHISH

if Statement

Qaysi componentni ko‘rsatishni tanlash uchun if JavaScript operatoridan foydalanishimiz mumkin.

Misol:

Biz ushbu ikkita componentdan foydalanamiz:

function MissedGoal() {
  return <h1>MISSED!</h1>;
}

function MadeGoal() {
  return <h1>Goal!</h1>;
}

Misol:

Endi biz shartga qarab qaysi componentni ko‘rsatishni tanlaydigan boshqa component yaratamiz:

function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}

createRoot(document.getElementById('root')).render(
  <Goal isGoal={false} />
);

Misolni ishga tushirish »

isGoal atributini true ga o‘zgartirib ko‘ring:

Misol:

createRoot(document.getElementById('root')).render(
  <Goal isGoal={true} />
);

Misolni ishga tushirish »



Mantiqiy && Operator

React componentini shartli ko‘rsatishning yana bir usuli && operatoridan foydalanishdir.

Quyidagi misolda sarlavha faqat props.brand xususiyati bo‘sh bo‘lmasa ko‘rsatiladi:

Misol:

&& ning o‘ng tomoni faqat chap tomoni to‘g‘ri bo‘lsa ko‘rsatiladi:

function Car(props) {
  return (
    <>
      {props.brand && <h1>My car is a {props.brand}!</h1>}
    </>
  );
}

createRoot(document.getElementById('root')).render(
  <Car brand="Ford" />
);

Misolni ishga tushirish »

Agar props.brand rost deb baholansa, && dan keyingi ifoda ko‘rsatiladi.

Try emptying the brand property:

Misol:

createRoot(document.getElementById('root')).render(
  <Car />
);

Misolni ishga tushirish »


Uchlik operator

Elementlarni shartli ko‘rsatishning yana bir usuli uchlik operatordan foydalanishdir.

condition ? true : false

Biz maqsad misoliga qaytamiz.

Misol:

MadeGoal componentini qaytaring, agar isGoal bu true , aks holda MissedGoal componentini qaytaring:

function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}

createRoot(document.getElementById('root')).render(
  <Goal isGoal={false} />
);

Misolni ishga tushirish »

Qo‘shimcha ma’lumot olish uchun uchlik operator bo‘limiga qarang.



W3Schools Pathfinder

Yutuqlaringizni kuzating – bu bepul!