Reputation: 117
I am new to react, I am working on a school project. In it, I am using Array.map
method to render my component in DOM. It's working fine but I have a little confusion with map()
method on the array. When I was learning Javascript I used Array.map
and I was storing a new Array from map()
method into a variable. for example const newArray = Array.map(e => e*2)
. So from MDN documents, I know map returns a new array. So now in react I saw some example and they are not storing Array.map
result in a new variable so where is this new array exist after mapping the old array, which got modified, they are just using Array.map(e => e*2)
not storing returned new array in any variable? For an example below where are they storing returned new array after mapping on incompleteTodos
.
So, Am I missing something here from Array.map method? P.S Below code is working fine.
const incompleteTodos = this.state.todos.filter(todo => !todo.completed);
<div className="todos">
{incompleteTodos.length > 0 && <h2 className="incomplete">Incomplete</h2> }
{
incompleteTodos.map(todo => (
<Todo key={todo.id} removeTodo={this.removeTodo} completeTodo={this.completeTodo} todo={todo}/>
))
}
Upvotes: 3
Views: 650
Reputation: 499
Printing variable automatically is programmed inside render()
function in JSX it works. This is the special of the ReactJS that refrained of creating too much variable for using. So if you have the code like this:
render() {
return(
<h1>{1+1}</h1>{// It will print '2' on the browser}
);
}
But the way using Array.map()
as a variable still decent and acceptable but the code you showed above seems better to work with react code so don't worry about that.
Happy Coding!
Upvotes: 2
Reputation: 6335
The map
method is indeed returning an array of Todo
components. This array is used by React to render the items.
The code you posted is equivalent to:
const incompleteTodos = this.state.todos.filter(todo => !todo.completed);
const items = incompleteTodos.map(todo => (
<Todo key={todo.id} removeTodo={this.removeTodo} completeTodo={this.completeTodo} todo={todo} />
));
<div className="todos">
{incompleteTodos.length > 0 && <h2 className="incomplete">Incomplete</h2> }
{items}
Upvotes: 1
Reputation: 402
Check out the example below,
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
const myTodos = [<div>Hi1</div>,<div>Hi2</div>,<div>Hi3</div>,]
// Created a array to return
class App extends Component {
render() {
return (
<div className="App">
{myTodos}
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
Here is the link for more reference, reactjs.org/docs/lists-and-keys.html
Upvotes: 1