Simple todo app using ReactJS and MobX
1. Create a new ReactJS app using create-react-app. You can use the following command in your terminal:
npx create-react-app todo-app
2. Install the necessary dependencies:
cd todo-app
npm install mobx mobx-react
3. Create a new file called TodoStore.js
in the src
directory with the following code:
import { makeObservable, observable, action } from 'mobx';
class TodoStore {
todos = [];
constructor() {
makeObservable(this, {
todos: observable,
addTodo: action,
removeTodo: action,
completeTodo: action,
});
}
addTodo = (todo) => {
this.todos.push({
id: Math.random(),
text: todo,
completed: false,
});
};
removeTodo = (todo) => {
this.todos = this.todos.filter((t) => t.id !== todo.id);
};
completeTodo = (todo) => {
todo.completed = !todo.completed;
};
}
const store = new TodoStore();
export default store;
4. Create a new file called TodoList.js
in the src
directory with the following code:
import React, { useState } from 'react';
import { observer } from 'mobx-react';
import todoStore from './TodoStore';
const TodoList = observer(() => {
const [todo, setTodo] = useState('');
const handleInputChange = (e) => {
setTodo(e.target.value);
};
const handleAddTodo = (e) => {
e.preventDefault();
todoStore.addTodo(todo);
setTodo('');
};
const handleRemoveTodo = (todo) => {
todoStore.removeTodo(todo);
};
const handleCompleteTodo = (todo) => {
todoStore.completeTodo(todo);
};
return (
<div>
<form onSubmit={handleAddTodo}>
<input type="text" value={todo} onChange={handleInputChange} />
<button type="submit">Add Todo</button>
</form>
<ul>
{todoStore.todos.map((todo) => (
<li key={todo.id}>
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
</span>
<button onClick={() => handleRemoveTodo(todo)}>Remove</button>
<button onClick={() => handleCompleteTodo(todo)}>Complete</button>
</li>
))}
</ul>
</div>
);
});
export default TodoList;
5. Update the App.js
file with the following code:
import React from 'react';
import TodoList from './TodoList';
function App() {
return (
<div className="App">
<h1>Todo App</h1>
<TodoList />
</div>
);
}
export default App;
6. Run the app using the following command:
npm start
Happy Learning!! Happy Coding!!
Comments