Assignments Of Day 9: Lists and Keys in React

Rashmi Mishra
0

 Assignments Of Day 9: Lists and Keys in React

Assignments Based on "Lists and Keys" in React

Assignment 1: Rendering a List of Fruits

Task:

  • Create a React component that renders a list of fruits. Use the map() function to iterate over an array of fruit names and display them as a list. Each list item should have a key prop.

Steps:

1.  Create an array called fruits with at least 5 fruit names (e.g., ["Apple", "Banana", "Cherry", "Date", "Elderberry"]).

2.  Use the map() method to loop through the array.

3.  Inside the map() method, return a <li> element for each fruit with a key prop set to its index in the array (for simplicity, use the array index as the key in this example).

4.  Display the list of fruits inside an unordered list (<ul>).

Solution:

jsx

Copy code

import React from 'react';

 

const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];

 

const FruitList = () => {

  return (

    <div>

      <h2>Fruit List</h2>

      <ul>

        {fruits.map((fruit, index) => (

          <li key={index}>{fruit}</li>

        ))}

      </ul>

    </div>

  );

}

 

export default FruitList;

Explanation:

  • The map() function is used to iterate through the fruits array.
  • The key={index} ensures that each li element is uniquely identified for React's internal tracking.

Assignment 2: Using Unique Keys with Dynamic Data

Task:

  • Modify the above fruit list to use unique id values instead of the array index. The data structure should contain an id for each fruit.

Steps:

1.  Modify the fruits array to store objects, where each object contains a name and id (e.g., { id: 1, name: 'Apple' }).

2.  Modify the map() method to use fruit.id as the key for each list item.

3.  Render the fruit name inside each list item.

Solution:

jsx

Copy code

import React from 'react';

 

const fruits = [

  { id: 1, name: 'Apple' },

  { id: 2, name: 'Banana' },

  { id: 3, name: 'Cherry' },

  { id: 4, name: 'Date' },

  { id: 5, name: 'Elderberry' }

];

 

const FruitList = () => {

  return (

    <div>

      <h2>Fruit List</h2>

      <ul>

        {fruits.map(fruit => (

          <li key={fruit.id}>{fruit.name}</li>

        ))}

      </ul>

    </div>

  );

}

 

export default FruitList;

Explanation:

  • We replaced the array of strings with an array of objects, where each object contains a unique id.
  • The key={fruit.id} ensures that each list item has a stable, unique identifier, which improves performance.

Assignment 3: Deleting Items from a List

Task:

  • Create a React component that renders a list of tasks. Each task should have a delete button. When the delete button is clicked, the corresponding task should be removed from the list.

Steps:

1.  Create a tasks array with at least 3 objects, each having an id and a task property (e.g., { id: 1, task: 'Buy groceries' }).

2.  Display the tasks in a list using the map() function.

3.  For each task, create a delete button that removes the task from the array when clicked.

4.  Use the key prop with each task to ensure efficient rendering.

Solution:

jsx

Copy code

import React, { useState } from 'react';

 

const TaskList = () => {

  const [tasks, setTasks] = useState([

    { id: 1, task: 'Buy groceries' },

    { id: 2, task: 'Walk the dog' },

    { id: 3, task: 'Clean the house' }

  ]);

 

  const deleteTask = (id) => {

    const filteredTasks = tasks.filter(task => task.id !== id);

    setTasks(filteredTasks);

  };

 

  return (

    <div>

      <h2>Task List</h2>

      <ul>

        {tasks.map(task => (

          <li key={task.id}>

            {task.task}

            <button onClick={() => deleteTask(task.id)}>Delete</button>

          </li>

        ))}

      </ul>

    </div>

  );

}

 

export default TaskList;

Explanation:

  • The useState hook is used to manage the list of tasks.
  • The deleteTask function filters out the task with the matching id from the tasks array and updates the state with the filtered list.
  • Each task is displayed with a delete button that calls deleteTask when clicked.


Tags

Post a Comment

0Comments

Post a Comment (0)