Array To List in Reactjs

image.png

prerequisite: reactjs.org/docs/lists-and-keys.html map function in js : This function will help us to loop through the entire array and helps us to generate a new array with some operations on it.

App.js

import "./App.css";
import ArrayToList from "./ArrayToList";


export default function App() {
  return (
    <div className="App">
      <div className="ArrayToList">
        <h1> Array To List in React</h1>
        <ArrayToList />
      </div>
    </div>
  );
}

ArrayToList.js

import React from "react";
const chars=['a','b', 'c', 'd'];
function ArrayToList() {
  const nums = [5, 6, 7, 8];
  const NList = nums.map((num) => <li> {num}</li>);
  const CList = chars.map((char) => <li> {char}</li>);
  return (
    <div>
      <ol>{NList}</ol>
      <ul>{CList}</ul>
    </div>
  );
}
export default ArrayToList;

The code will work as fine for now, but there is an issue there is no key, so by default react assign index as key and WE SHOULD NOT USE INDEX AS KEYS, as it affects the performance , so what to do instead. read detailed Article here: robinpokorny.medium.com/index-as-a-key-is-a.. (use of nanoid as keys, instead of the index)

Keys are important so we will modify the code with key

import React from "react";
const chars=['a','b', 'c', 'd'];
function ArrayToList() {
  const nums = [5, 6, 7, 8];
  const NList = nums.map((num) => <li key={num.toString()}> {num}</li>);
  const CList = chars.map((char) => <li key={char}> {char}</li>);
  return (
    <div>
      <ol>{NList}</ol>
      <ul>{CList}</ul>
    </div>
  );
}
export default ArrayToList;

I would still recommend one to use nanoid or other component to use as key, in above example if character repeats, we will lost uniqueness and react will warn us as keys should be unique. in next exercise will create custom list componet