Categories:Viewed: 99 - Published at: 9 months ago

Javascript Syntax Extension (JSX), is a JavaScript extension developed and popularized by the React framework that allows you to structure the rendering of elements. It essentially makes it easier to write HTML code in React (describe the UI), and due to its flexibility, JSX has been adopted by other popular frameworks such as Vue.js throughout the years. In this short tutorial, we will take a look at how to loop inside react JSX elements, working with the following todos array:

const todos = [
  { id: 1, text: "Learn React", status: "completed" },
  { id: 2, text: "Do something", status: "incomplete" },
  { id: 3, text: "Do something else", status: "incomplete" },
];

Loop in React JSX

The map() function introduced in ES6 is the only preferred method for looping in JSX:

{
  todos.map((todo) => (

      {todo.text} - {todo.status}

  ));
}

For each element in the array, we map its text and status fields to content within a <p> element, whose key is mapped to the id field. This will generate the following markup result:

Learn React - completed
Do something - incomplete
Do something else - incomplete

Understanding the key Attribute

Depending on the framework/linting tool you are using, if you don't use a unique key value for each <p> element, you're likely to encounter a warning:

Warning: Each child in a list should have a unique "key" prop

Keys in the React loop help identify which items have been changed, added or removed, and it is important to give the parent elements inside a loop unique keys to help give a stable identity to the element or component. Like in our todos array example, we can specify each todo id as the key:

{
  todos.map((todo) => (
    <div key="{todo.id}">

        {todo.text} - {todo.status}

    </div>
  ));
}

If the item you’re trying to loop through does not have a unique element, such as a unique id - it is a common convention to use the index returned by the map() function for each iterated element instead, ensuring unique element identification without changing your domain model:

{
  todos.map((todo, index) => (
    <div key="{index}">

        {todo.text} - {todo.status}

    </div>
  ));
}

Conclusion

In this short tutorial, we’ve covered the basics of looping in React JSX, how keys work, as well as how to add a unique key to iterable elements.

Reference: stackabuse.com

TAGS :