Categories
Uncategorized

List and Keys in React.JS

Convert array to list: Let us convert array to list in React.JS. 

1) First we have a const array element named arr_numbers. 

const arr_numbers = [1, 2, 3, 4, 5];

2) This array will be fetched by ReactDOM and assigned value numbers: 

ReactDOM.render(
<NumberList numbers = {arr_numbers}/>,
document.getElementById('root')
);

3) While the ReactDOM get array, a function NumberList() will be made to get this props so that it can be put in list structure, and finally it will be returned to reactDOM: 

function NumberList(props){
const list = props.numbers;
const listItems = list.map(
(number) => <li key={number.toString()}>
{number}
</li>
);
return (
<ul>{listItems}</ul>
);
}

It is a javascript method to convert to convert array to list: list.map((number) => <li> {number} </li> and it has been used in NumberList(props) function. Keys help react identify values changed in array, so ‘key’ has been assigned value of number, after converting it to string form. 


If we use keys in arrays, they should be unique among their siblings. It help to use them all at once with common code. For example, we have keys:  id, title and contents in following array: 

const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'}
];

In ReactDOM, we fetch value of this array in property posts: 

ReactDOM.render(
<Blog posts={posts} />,
document.getElementById('root')
);

Now we can create a function Blog() with which fetch its property posts: 

function Blog(props) {
const content = props.posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{content}
</div>
);
}

We created a constant ‘content’ in function and mapped props value of posts. We fetched id, title and content as {post.id} assigned as React key, {post.title} and {post.content} and put it in html structure to display all content of array by return() in function and the function gets rendered in ReactDOM.


Map() in JSX: JSX allows to embed any expression in curly braces. So we could use map function directly in return() inside curly braces as 

{list.map(
(number) => <li key={number.toString()}>
{number}
</li>
)}

Rest of the code is similar to first example of this page. Overall code is: 

const arr_numbers = [1, 2, 3, 4, 5];

ReactDOM.render(
<NumberList numbers = {arr_numbers}/>,
document.getElementById('root')
);

function NumberList(props){
const list = props.numbers;

return (
<ul>
{list.map(
(number) => <li key={number.toString()}>
{number}
</li>
)}
</ul>
);
}

Leave a Reply

Your email address will not be published. Required fields are marked *