Tutorials/React/GET STARTED
Lesson

React Conditional Rendering and List

GET STARTED/React

React Conditional Rendering

Show different UI based on condition

Using if Statement

javascript
function Goal(props) {

  if (props.isGoal) {

    return <h1>Goal</h1>
  }
  return <h1>Missed</h1>
}

Using && Operator

javascript
function Car(props) {
  return (
    <>
      {props.brand && <h1>{props.brand}</h1>}
    </>
  )
}

If value is true then show element

Using Ternary Operator

javascript
function Goal(props) {
  return (
    <>
      {props.isGoal ? <h1>Goal</h1> : <h1>Missed</h1>}
    </>
  )
}

React Lists

  • Used to show multiple items

  • We use loop to display data

Using map method

javascript
function App() {
  const cars = ["Ford", "BMW", "Audi"]

  return (
    <ul>
      {cars.map((car) => <li>{car}</li>)}
    </ul>
  )
}
  • map is used to loop array

  • Key is required for each item

  • It helps React update efficiently

Example with Key

plaintext
function App() {
  const cars = [
    { id: 1, brand: "Ford" },
    { id: 2, brand: "BMW" }
  ]

  return (
    <ul>
      {cars.map((car) => (
        <li key={car.id}>{car.brand}</li>
      ))}
    </ul>
  )
}

Using Index as Key

plaintext
{cars.map((car, index) => (
  <li key={index}>{car}</li>
))}

Use only when list is fixed

React Conditional Rendering and List | React | Softcrayons Tech Solutions