Dynamic React List Component

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create a dynamic list component in React using the DataList component. With this component, we can render an array of primitive values as an ordered or unordered list. By the end of the lab, you will have a better understanding of how to use Array.prototype.map() and conditionally render elements based on props in React.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/list_keys("`Lists and Keys`") subgraph Lab Skills react/jsx -.-> lab-38347{{"`Dynamic React List Component`"}} react/list_keys -.-> lab-38347{{"`Dynamic React List Component`"}} end

Data List

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

This function renders a list of items from an array of primitive values. It can be used to conditionally render an ordered or unordered list based on the value of the isOrdered prop. To render each item from the data array, it uses Array.prototype.map() to create a <li> element with a unique key for every item.

const DataList = ({ data, isOrdered = false }) => {
  const list = data.map((value, index) => (
    <li key={`${index}_${value}`}>{value}</li>
  ));

  return isOrdered ? <ol>{list}</ol> : <ul>{list}</ul>;
};

Here's an example of how you can use this component:

const names = ["John", "Paul", "Mary"];
ReactDOM.createRoot(document.getElementById("root")).render(
  <>
    <DataList data={names} />
    <DataList data={names} isOrdered={true} />
  </>
);

In this example, we're passing an array of names to the DataList component and rendering it twice. The first time, we're rendering an unordered list, while the second time we're rendering an ordered list.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Data List lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like