Home>Article>Web Front-end> How to use map method in react

How to use map method in react

WBOY
WBOY Original
2022-06-28 16:21:56 4602browse

In react, the map method is used to traverse and display a list of similar objects of the component; the map method is not unique to react and can call standard JavaScript functions on any array. The map method calls each element of the array. Call the provided function to create an array with elements.

How to use map method in react

The operating environment of this tutorial: Windows 10 system, react17.0.1 version, Dell G3 computer.

How to use the map method in react

Map is a data collection type in which data is stored in the form of pairs. It contains a unique key to which the values stored in the map must be mapped. We cannot store duplicate pairs in map(), this is because each stored key is unique and it is mainly used for fast searching and finding data.

In React, the map method is used to traverse and display a list of similar objects in a component. Map is not unique to React. On the contrary, it is a standard JavaScript function that can be called on any array. The map() method creates a new array by calling the provided function on each element in the calling array.

Example

In the given example, map() function accepts an array of numbers and doubles its values, we allocate the new array returned by map() Give variable doubleValue and log it.

var numbers = [1, 2, 3, 4, 5]; const doubleValue = numbers.map((number)=>{ return (number * 2); }); console.log(doubleValue);

In React, the map() method is used for:

1. Traverse list elements.

Example

import React from 'react'; import ReactDOM from 'react-dom'; function NameList(props) { const myLists = props.myLists; const listItems = myLists.map((myList) => 
  • {myList}
  • ); return (

    React Map例子

      {listItems}
    ); } const myLists = ['A', 'B', 'C', 'D', 'D']; ReactDOM.render( , document.getElementById('app') ); export default App;

    2. Iterate through list elements by key.

    Example

    import React from 'react'; import ReactDOM from 'react-dom'; function ListItem(props) { return 
  • {props.value}
  • ; } function NumberList(props) { const numbers = props.numbers; const listItems = numbers.map((number) => ); return (

    React Map例子

      {listItems}
    ); } const numbers = [1, 2, 3, 4, 5]; ReactDOM.render( , document.getElementById('app') );

    [Related recommendations:javascript video tutorial,web front-end

    The above is the detailed content of How to use map method in react. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn