Components

Let's build our components. We'll start by breaking our component down into the main component, the ToDo list component, the AddTodo component, and the Footer component. The code must be self-explanatory.

App.js is the main container component that gets the TODO states and passes them to the required components. We use the Redux connect function to connect our container and components. This should make sense, having read Chapter 1, Understanding Redux. Let's examine our Todo.js file, as follows:

//Todo.js
import React, { PureComponent } from "react";
import PropTypes from "prop-types";
import { deleteTodo, completeTodo } from "../actions/todos";
import cn from "classnames";

export default class Todo extends PureComponent {
static propTypes = {
todo: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired
};

render() {
const { id, text, isCompleted } = this.props.todo.toObject();
const classNames = cn("todo", {
completed: isCompleted
});
return (
<li className="list-group-item">
<span
className={classNames}
onClick={() => this.props.dispatch(completeTodo(id))}
>
{text}
</span>
<div
className="close"
onClick={() => this.props.dispatch(deleteTodo(id))}
>
&times;
</div>
</li>
);
}
}

There's nothing new, is there? We know what actions, reducers, and dispatch functions are. If you feel stuck, feel free to visit Chapter 1Understanding Redux, again. Hey, if it makes you feel better, no one can understand the whole concept in one go. So, it is okay to read the chapter again and again, until it starts to make sense to you. One important thing that I would like to point out is the use of PureComponent, instead of Component. Why do you think I used PureComponent? The React documentation site explains that in a decent way. Check out the following screenshot, and see if it makes sense to you:

Our components for AddToDo.js can be written as follows. The code is self-explanatory, and it does not contain anything very complex:

//AddTodo.js
import React, { Component } from "react";
import PropTypes from "prop-types";

import { addTodo } from "../actions/todos";

export default class AddTodo extends Component {
static propTypes = {
dispatch: PropTypes.func.isRequired
};

shouldComponentUpdate() {
// component has no props or state change so it is safe to just return `false`
return false;
}

addTodo(e) {
e.preventDefault();
const input = this.refs.todo;
const value = input.value.trim();
if (value) {
this.props.dispatch(addTodo(value));
input.value = "";
}
}

render() {
return (
<div>
<form onSubmit={e => this.addTodo(e)}>
<input
className="form-control"
type="text"
placeholder="Enter ToDo"
ref="todo"
/>
</form>
<br />
</div>
);
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset