Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created November 12, 2020 15:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/d21a6c4ee9a7106afbc9d60723e8df39 to your computer and use it in GitHub Desktop.
Save cferdinandi/d21a6c4ee9a7106afbc9d60723e8df39 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>React Todos in Vanilla JS</title>
<style type="text/css">
body {
margin: 0 auto;
max-width: 40em;
width: 88%;
}
label,
input {
display: block;
}
input {
margin-bottom: 1em;
}
</style>
</head>
<body>
<h1>React Todos in Vanilla JS</h1>
<ul id="todo-list"></ul>
<form id="add-todos">
<label for="new-todo">What needs to be done?</label>
<input id="new-todo">
<button>
Add #<span id="add-count"></span>
</button>
</form>
<script src="https://cdn.jsdelivr.net/npm/reefjs/dist/reef.min.js"></script>
<script>
//
// Variables
//
var addTodos = document.querySelector('#add-todos');
//
// Methods
//
/**
* Save todos to localStorage
*/
var saveTodos = function () {
localStorage.setItem('todos', JSON.stringify(store.data.todos));
};
/**
* Load todos from localStorage
*/
var loadTodos = function () {
var saved = localStorage.getItem('todos');
store.data.todos = saved ? JSON.parse(saved) : [];
};
/**
* Handle submit events
* @param {Event} event The event object
*/
var submitHandler = function (event) {
// Stop the form from reloading the page
event.preventDefault();
// Get the todo item field
var text = addTodos.elements['new-todo'];
// If there's no text in the field, do nothing
if (!text || !text.value.length) return;
// Inject the todo item into the UI
store.data.todos.push({
text: text.value,
id: new Date().getTime()
});
// Clear the field
text.value = '';
// Save todos to localStorage
saveTodos();
};
//
// Components
//
var store = new Reef.Store({
data: {}
});
var todoList = new Reef('#todo-list', {
store: store,
template: function (props) {
return props.todos.map(function (todo) {
return `<li id="${todo.date}">${todo.text}</li>`;
}).join('');
}
});
var count = new Reef('#add-count', {
store: store,
template: function (props) {
return props.todos.length + 1;
}
});
//
// Event Listeners
//
// Render initial UI
loadTodos();
// Listen for form submissions
addTodos.addEventListener('submit', submitHandler);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment