Full Stack Development

Lists

by Tomas Trescak t.trescak@westernsydney.edu.au

Lists

/

Introduction

      import { render } from 'react';
function NumberList({ numbers }) {
  return (
    <ul>
      {numbers.map(
        (number) => <li>{number}</li>
      )}
    </ul>
  );
}

// Usage
const numbers = [1, 2, 3, 4, 5];
function App() {
  return <NumberList numbers={numbers} />;
}

render(<App />)
    

Lists

/

Keys

      import React, { render } from 'react';
function NumberList({ items }) {
  return (
    <ul>
      {items.map(
        (item) => <li>{number}</li>
      )}
    </ul>
  );
}
 
// Usage
const numbers = [1, 2, 3, 4, 5];
function App() {
  return <NumberList items={numbers} />;
}
 
render(<App />)
    

Lists

/

Keys

      import { render } from 'react';

const todos = [
  { id: 1, text: "Some Todo" }, 
  { id: 2, text: "Other Todo" }
];

function ToDoList({ todos }) {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}

// Usage
function App() {
  return <ToDoList todos={todos} />;
}

render(<App />)
    

Lists

/

Keys - Problem Example

      import { useState } from "react";

let uid = 3;

// noprotect
function Item({ name, id }) {
  return (
    <div>
      <label>{name}: </label>
      <input 
        type='text' 
        id={id} 
      />
    </div>
  )
}

function App()  {
  const [state, setState] = useState([
    {name: '1', id: 1},
    {name: '2', id: 2}
  ])
  
  function addItem() {
    const id = uid ++;
    setState(
      [ {name: id.toString(), id} , ...state]
    );
  }
  
  return (
    <div>
      <b>How to use: </b>
      First write something in the inputs. Then hit <em>Add item</em> and see what happens.
      <hr/>
      <button className='btn btn-primary' onClick={addItem}><b>Add item</b> to the beginning of the list</button>
    

      <h3>Dangerous <code>key=index</code></h3>
      <form className="form-horizontal">
        {state.map((todo, index) =>
          <Item 
            name={todo.name}
            id={'d_' + todo.id}
            key={index} 
          />
        )}
      </form>
      
      <hr />

      <h3>Better <code>key=id</code></h3>
      <form className="form-horizontal">
        {state.map((todo) =>
          <Item 
          name={todo.name}
          id={'s_' + todo.id}
          key={todo.id} />
        )}
      </form>
    </div>
  )
}

render(<App />)
    

Lists


  • Best Practices
    • Always use keys when rendering lists
    • Keep components small and focused; let a dedicated component render list items if they are complex.
  • Common Mistakes
    • Using indices as keys in arrays where the order or items can change.
    • Forgetting to handle cases where the list might be empty or data might not be immediately available due to asynchronous loading.

Lists

/

Empty Lists

      function ArticleList({ articles }) {
  if (!articles.length) {
    return <p>No articles available.</p>;
  }

  return (
    <ul>
      {articles.map((article) => 
        <li key={article.id}>
          {article.title}
        </li>
      )}
    </ul>
  );
}

// Usage
function App() {
  return <ArticleList articles={[]} />;
}

render(<App />)
    

Lists

/

Handling Fragments

      import { Fragment } from 'react';

function TagList({ tags }) {
  return (
    <>
      {tags.map((tag) => 
        <Fragment key={tag.id}>
          {tag.name}, {' '} 
        </Fragment>
      )}
    </>
  );
}

// Usage
function App() {
  return <TagList tags={[
    { id: 1, name: '#Tag1'},
    { id: 2, name: '#Tag2'}
  ]} />;
}

render(<App />)