Following is the simple approach to access objects of array.map() to another function in React
We can directly call the function in array.map() and pass the object in that function to return the required value.
Setting up environment and Execution:
Step 1: Create React App command
npx create-react-app foldername
Step 2: After creating your project folder, i.e., folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
FIlename: App.js
Javascript
import React, { Component } from "react" ; class App extends Component { constructor(props) { super (props); this .state = { books: [ { title: "Book Title 1" , USD: 10 }, { title: "Book Title 2" , USD: 20 }, ], }; } // We want to pass books object in this function // and return Rupees value usdToRupees = (book) => { return book.USD * 75; }; render() { return ( <div> { this .state.books && this .state.books.map((book) => { return ( <div> <h2>{book.title}</h2> <p>USD = {book.USD}</p> { /* We are passing book object to the function */ } <p>Rupees = { this .usdToRupees(book)}</p> <hr></hr> </div> ); })} </div> ); } } export default App; |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output: