Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJakub Kašpar
16,383 PointsHow to stay DRY in React?
Hello everyone,
I am trying to build a simple to-do app based on one of treehouse courses (Interactive Web Pages with JavaScript).
I store all my tasks in an array like this:
var TASKS = [
{
name: "Pay Bills",
completed: false,
id: 1,
},
{
name: "Go shopping",
completed: false,
id: 2,
},
{
name: "Pick up something",
completed: false,
id: 3,
},
{
name: "Drink Coffee",
completed: true,
id: 4,
},
];
and I want to render them in separate sections (to-do, done) like this:
render: function() {
return (
<div className="to-do">
<Section title={this.props.title}>
<AddTodoForm onAdd={this.onTodoAdd} />
</Section>
<Section title="to-do">
<ul className="tasks-list">
{this.state.tasks
.filter(function(task, index) {
return task.completed === false;
})
.map(function(task, index) {
return(
<Task
name={task.name}
key={task.id}
completed={task.completed}
onCompleted={function() {this.onCompletedTask(index)}.bind(this)}
onRemove={function() {this.onRemoveTask(index)}.bind(this)}
/>
);
}.bind(this))}
</ul>
</Section>
<Section title="done">
Here I want to render only done tasks
</Section>
</div>
);
}
My question is, what is the best way how to render the done tasks without repeating the whole filter/map function?
Thanks for your advice, Jakub
1 Answer
Seth Kroger
56,413 PointsYou could break out the anonymous function in map(), either as a member of the class or assigning it to a variable in the render method. Then it could be reused for both. You could also do a function that takes in the todos and an areCompleted boolean then returns the result of filter and map together.