
Quick Contact
React Tutorial
- React JS Introduction
- How to install react?
- React Features
- React vs React Native
- React JS VUE Application
- State V/S Props
- React Props
- REACT STATE
- React JSX?
- Conditional Rendering
- React Constructor
- Props Validation
- React Component API
- React Forms
- React Event
- Flux v/s MVC
- React Flux Concept
- React Fragment
- React Lists and Keys
- Error Boundaries
- React Portals
- React Animation
- React Redux
- React CSS
- React Refs
- React Router
Questions & Answers
React Lists and Keys
When we render list of items react involving in the console. Each child in the array should have unique key prop. As there are numbers of ways using JavaScript map function. In code < li> element return denoted for list (li) for each item. From following code- array of elements is assigning to list items and included entire list items array inside < ul> element as-:
Const numbers = [1, 2, 3, 4, 5]; Const listitems = numbers.map ((number) => < li>{number}< /li> ); ReactDOM.render( < ul>{listitems}< /ul>, Document.getElementById(‘root’) ); Suppose following code creates bullet lists of numbers in array. Const numbers = [1, 2, 3, 4, 5]; Const listitems = numbers.map((number) => < li>{number}< /li> ); ReactDOM.render( < ul>{listitems}< /ul> Document.getElementById(‘root’) ); Now take previous list into a component that accepts array of numbers and outputs list of elements. Function numberlist(prop){ Const numbers = props.numbers; Const listitems = numbers.map((number) => < li>{number}< /li> ); Return ( < ul>{listitems}< /ul> ); } Const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( < NumberList numbers={numbers}/> Document.getElementById(‘root’) );
When you run this code a warning shows –that- Each child in a list should have a unique “Key” prop.
So here move forward towards the Key.
Key is a special attribute that need to include in creating lists of elements. Lets assign key to list items file that is numbers.map.
Function NumberList(props) { Const numbers = props.number; Const listitems = numbers.map((number) => < li key={number.toString()}> {number} < /li> ); Return ( < ul>{listitems}< /ul> ); } Const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( < Numberlist numbers={numbers}/> Document.getElementById(‘root’) );
So key is string attribute that identifies items in list. Key helps to identify that which item is changed or added. Key should be given to elements for stable identity. Key donot need to be globally unique among siblings. Same keys can produce two different arrays. If you have two elements i.e. ‘sidebar’ and ‘content’. Using same id for these respective elements is fine because these are two different react elements.
As key hit to react so key donot pass to the components. Key should be passed as a prop with different name as-:
Const content = posts.map((post) => < post Key= {post.id} Id= {post.id} Title= {post.title}/> );
Apply now for Advanced React Js Course