Conditionals

React Conditionals Rendering

React Shartli Renderlash

React-da komponentlarni shartli ravishda renderlash mumkin.

Buni amalga oshirishning bir necha usuli mavjud.

if Operatoridan Foydalanish

JavaScript if operatoridan foydalanib, qaysi komponentni renderlashni aniqlashimiz mumkin.

Misol: Ikki komponentni ishlatamiz:

function MissedGoal() {
  return <h1>QO'LGA KIRMADI!</h1>;
}
 
function MadeGoal() {
  return <h1>Gol!</h1>;
}

Misol: Endi shartga qarab qaysi komponentni renderlashni tanlaydigan boshqa komponent yaratamiz:

function Goal(props) {
  const isGoal = props.isGoal;
  if (isGoal) {
    return <MadeGoal/>;
  }
  return <MissedGoal/>;
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

isGoal atributini true ga o'zgartirib ko'ring:

Misol:

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

&& Operatoridan Foydalanish

React komponentini shartli ravishda renderlashning yana bir usuli && operatoridan foydalanishdir.

Misol: JSX ichida JavaScript ifodalarini qavslar yordamida qo'shishimiz mumkin:

function Garage(props) {
  const cars = props.cars;
  return (
    <>
      <h1>Garaj</h1>
      {cars.length > 0 &&
        <h2>
          Sizning garajingizda {cars.length} ta mashina bor.
        </h2>
      }
    </>
  );
}
 
const cars = ['Ford', 'BMW', 'Audi'];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

Agar cars.length > 0 ifodasi true ga teng bo'lsa, && operatoridan keyingi ifoda renderlanadi.

Misol: cars massivini bo'shatib ko'ring:

const cars = [];
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Garage cars={cars} />);

Ternar Operatoridan Foydalanish

Elementlarni shartli ravishda renderlashning yana bir usuli ternar operatoridan foydalanishdir.

condition ? true : false

Gol misoliga qaytaylik.

Misol: Agar isGoal true bo'lsa, MadeGoal komponentini, aks holda MissedGoal komponentini qaytarish:

function Goal(props) {
  const isGoal = props.isGoal;
  return (
    <>
      { isGoal ? <MadeGoal/> : <MissedGoal/> }
    </>
  );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Goal isGoal={false} />);

Qo'shimcha ma'lumot olish uchun ternar operatori bo'limiga qarang.

Ushbu sahifada

GitHubda tahrirlash