Create a React component named MapArray, which will do the job of mapping the items of an array to a React component.
First, create an index.html file where the React application will be rendered:
- Create a new file named index.html
- Add the following HTML code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Rendering Lists</title> </head> <body> <div role="main"></div> <script src="./lists.js"></script> </body> </html>
- Save the file
Then, perform the following steps to build the React application:
- Create a new file named lists.js.
- Import the React and ReactDOM libraries:
import * as React from 'react' import * as ReactDOM from 'react-dom'
- Define a functional component called MapArray that will expect to receive three properties: from, which is expected to be an array of values, mapToProps, which is expected to be a callback function for mapping values to properties, and lastly, children, which is expected to receive a React component where the values of the array will be mapped to:
const MapArray = ({ from, mapToProps, children: Child, }) => ( <React.Fragment> {from.map((item) => ( <Child {...mapToProps(item)} /> ))} </React.Fragment> )
- Define a TodoItem component that expects to receive two properties, done and label:
const TodoItem = ({ done, label }) => ( <li> <input type="checkbox" checked={done} readOnly /> <label>{label}</label> </li> )
- Define an array that contains a to-do list of object values:
const list = [ { id: 1, done: true, title: 'Study for Chinese exam' }, { id: 2, done: false, title: 'Take a shower' }, { id: 3, done: false, title: 'Finish chapter 6' }, ]
- Define a callback function that will map the array's object values to the expected properties of the TodoItem component. Rename the id property as key, and the title property as label:
const mapToProps = ({ id: key, done, title: label }) => ({ key, done, label, })
- Define a TodoListApp component that will make use of the MapArray component to create an instance of TodoItem for every item in the to-do list array:
const TodoListApp = ({ items }) => ( <ol> <MapArray from={list} mapToProps={mapToProps}> {TodoItem} </MapArray> </ol> )
- Render the application:
ReactDOM.render( <TodoListApp items={list} />, document.querySelector('[role="main"]'), )
- Save the file.