Why do we need React lists?
Lists are crucial features of an app. A list of tasks like a calendar app, a list of pictures like Instagram, a list of items to shop in a shopping cart, etc., are the numerous use-cases where lists are used to improve the performance. Imagine an app with a huge list of videos or pictures appearing as you scroll. This could hinder the app’s performance. As performance is an essential aspect, using lists would make sure that they are designed for optimal performance.
Lists are useful to improve or create the UI of any website. Lists are mainly used for illustrating or showcasing menus on a website, for instance, the navbar menu. IIn regular JavaScript, we use arrays for creating lists, and in React we can create lists similarly as we do in standard JavaScript.
Lists can be traversed and updated by using the map() function in JavaScript as shown in the code below:
<script type="text/javascript">
var numberexample = [1,2,3,4,5];
const updatedNumsExample = numberexample.map((number)=>{
return (number + 2);
});
console.log(updatedNumsExample);
</script>
The above code logs output to console as:
[3, 4, 5, 6, 7]
Traversing List using the Key in React
Each list item in our unordered list should have a unique key. A “key” is a special string attribute required when creating lists of elements in React. Keys are important to improve the performance of React app. Keys also help to identify which items have changed (added/removed/re-ordered).
import React from 'react';
import ReactDOM from 'react-dom';
function Navmenuexample(props)
{
const listexample = props.menuitems;
const updatedListExample = listexample.map((listItems)=>{
return(
<li key={listItems.toString()}>
{listItems}
</li>
);
});
return(
<ul>{updatedListExample }</ul>
);
}
const menuItemsexample = [1,2,3,4,5];
ReactDOM.render(
<Navmenuexample menuitemsexample = {menuItemsexample} />,
document.getElementById('root')
);
Know more about usereducer hook in React.
Rendering a List in React
Map() function
Lists are rendered by mapping data. We use the array’s map instance method for mapping. We can do that as follows:
import React from "react";
const people= [
{ firstName: "John", lastName: "Smith" },
{ firstName: "Bill", lastName: "Jones" },
{ firstName: "Roger", lastName: "Moore" }
];
const People= ({ firstName, lastName }) => (
<div>
{firstName} {lastName}
</div>
);
export default function App() {
return (
<div>
{people.map((p, i) => (
<People {...p} key={i} />
))}
</div>
);
}
The People array is called a map in App. We pass in a callback to return the People component in the map method with all the features of each people array entry passed in as props.
The key prop is required in React that can identify them properly. It’s a unique ID, but the array index can also be the value of the key prop.
<People firstName={p.firstName} lastName={p.lastName} key={i} />
The above code list firstName and LastName.
At the end below output is displayed on the screen:
John Smith
Bill Jones
Roger Moore
1. Dynamic Component Names
Dynamic components can be used in React. With React, it is easy to render dynamic components through JSX. We can render react dynamic components as follows:
import React from "react";
const first = ({ text }) => <p>{text} first</p>;
const second= ({ text }) => <p>{text} second</p>;
const components = {
first: First,
second: Second
};
export default function App() {
const [name, setName] = React.useState("foo");
const toggle = () => {
setName(name => (name === "first" ? "second" : "first"));
};
const Component = components[name];
return (
<>
<div>
<button onClick={toggle}>ToggleNames</button>
<Component text="helloExample" />
</div>
</>
);
}
We have the name state, as is set by the setName function. The toggle function calls setName to change the name.
const Component = components[name];
Returns the Component to render it. Click the toggle button, and the name should toggle as ‘hello first’ and ‘hello second’ displayed as the button is clicked.
2. Default Props
Default props make sure that there are some values set for our props.
To set the default props, the defaultProps property is used for each prop. Following code shows how to set default props for the People component that we have above:
import React from "react";
const people= [
{ firstName: "John", lastName: "Smith" },
{ firstName: "Bill", lastName: "Jones" },
{ firstName: "Roger", lastName: "Moore" },
{}
];
const People= ({ firstName, lastName }) => (
<div>
{firstName} {lastName}
</div>
);
People.defaultProps = {
firstName: "Default",
lastName: "Value"
};
export default function App() {
return (
<div>
{people.map((p, i) => (
<People {...p} key={i} />
))}
</div>
);
}
In the above code we have the default values set for firstName and lastName props.
People.defaultProps = {
firstName: "Default",
lastName: "Value"
};
Following id displayed on the screen:
John Smith
Bill Jones
Roger More
Default Value
We have an empty object in the people array, and it is in the last entry. The default values are rendered of whatever is passed in.
The important 'key' attribute
Preface
React developers when writing the code must have encountered this odious warning:
A Simple fix to remove the error above is to add key prop into the tag as below:
Do you know why this key prop is so important? Let’s explore and understand its significance in professional settings.
“Key” Prop
Keys help React to identify which details have been modified, added, or removed. Keys are passed as elements inside the array to provide the elements with a stable identity.
React provides a “diffing” algorithm through which updating components in react can be easily done on a website/application. The process of easy update of components using the diffing algorithm is defined as the “reconciliation” mechanism in React. To understand the significance of the key prop, Let us go step by step to understand it better.
1. Virtual DOM:
Virtual DOM in react is considered as the most important feature and this is the term used instead of real DOM.
The advantage of virtual DOM is that it is much faster and takes less memory than normal DOM. New updates/changes would have the real DOM re-render all elements i.e., updated and children element. On a different note, the virtual DOM would create a copy of the “actual” DOM and match or compare updated elements. This comparison mechanism is termed as “diffing”. React would then use the copy to conclude what needs to be updated.
Step 1: On new changes, the complete UI components would be re-rendered in the virtual DOM rep.
Step 2: Relating or comparing the virtual DOM and real DOM
Step 3: Following the real DOM is updated with changes
2. React iterates within the children of a DOM node:
In React utilizing virtual DOM, it iterates over both lists of children at the same time and creates a variation whenever there’s a variation or difference.
The following code:
function FrameworkList(props) {
const frameexample = props.frameexample;
const listJSFrameworks = frameworks.map(frameexample =>
<li>{frameexample}</li>
);
return (
<ul>{listJSFrameworks}</ul>
);
}
const frameexample = ["PHP", "Python"];
ReactDOM.render(
<FrameworkList frameexample={frameexample} />,
document.getElementById('root')
);
Our Array when printed would be as below:
<ul>
<li>PHP</li>
<li>Python</li>
</ul>
If array is updated as below:
<ul>
<li>PHP</li>
<li>Python</li>
<li>ASP.net</li>
</ul>
React would easily match the two arrays and with a slight change at the end, React would easily compare the array using the diffing algorithm, and the new change as <li>ASP.net</li> would easily be in the tree.
But when the new item is naively added i.e. at the beginning:
<ul>
<li>ASP.net</li> <- the new item
<li>React</li>
<li>Angular</li>
</ul>
React would take a while to realize the change i.e.<li>ASP.net</li>. After “mutating” the whole list and iterating the whole list, it would keep subtrees intact. But the newly added node would not get iterated easily. The “realization” is very inefficient and it is for this reason the key prop plays an important role.
3. “key” prop:
Using the key attribute helps React to quickly recognize the updates done in the tree.
The key attribute can be added like below:
<ul>
<li key="asp">ASP.net</li> <- the new item
<li key="php">PHP</li>
<li key="python">Python</li>
</ul>
Using id and map function the data would look as below:
const listJSFrameworks = frameworks.map(framework =>
<li key={framework.id}>{framework.name}</li>
const JsFrameworks = [
{
id: 1,
name: "ASP.net"
},
{
id: 2,
name: "PHP"
},
{
id: 3,
name: "Python"
}
];
Note: Keys are important for React and help to classify details that have been modified, added, or removed using the diffing algorithm.
Looking to level up your coding skills? Join our Python Scripting Online Course and unlock endless possibilities! Start coding like a pro with Python today. Don't miss out, enroll now!
Render nested lists based on a dataset
For nested lists, in react we have the ability to create a map within a map.
Here's an example of a list of users that have pets.
function App() {
const peoplevalues = [
{
name: Ram,
petsname: [
{ name: 'umbrella', type: 'rain' },
{ name: ‘coconut’, type: 'sheep' }
]
},
{
name: 'nicky',
petsname: [
{ name: 'hilo', type: 'dog' },
{ name: 'Hello', type: 'rabbit' }
]
}
];
return (
<div>
{peoplevalues.map((person, index) => (
<div key={index}>
<h2>{person.name}'s Petsname</h2>
{/* loop over the pets */}
<div>
{person.petsname.map((pet, i) => (
<p key={i}>
{pet.type} named {pet.name}
</p>
))}
</div>
</div>
))}
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
Output:
Ram’s Petsname
rain named umbrella
sheep named coconut
nicky's Petsname
dog named hilo
rabbit named Hello
Using Lists in React
While working on React Native apps, you will come across phases where you have to deal with arrays. These cases may include data from external APIs, feedback to your backend services, or generally, providing a list of data items to your component. React Native offers many unique benefits. However, there is no one-size-fits-all solution, and your choice of technology stack depends largely on your business idea, whether you are a start-up or a thriving business leader.