This will be a quick down and dirty tutorial on making a to-do list using React. If you’re anything like me and todo lists just really get you fired up, you can take a sneak peek at this bad boy in all it’s finished glory right here.
…I know pretty amazing stuff right?
Get Started with React
- Clone this repository
$ git clone https://github.com/seantbaier/react-todo-list.git
or download the zip.
2. Make sure you’re in the todo-list-starter-files directory you
$ -cd todo-list-starter-files
$ npm install or yarn
$ npm start or yarn start
Now one last step before we dive into the code and that is to install React Developer Tools which you can grab here. Once you have this installed, open chrome dev tools and you should see a tab labeled “React.” This is where you can inspect your React components and it makes debugging a lot easier.
Function Components (stateless)
Class Components (stateful)
Now on our form, we can type in items but we don’t really have a list yet. Let’s add some more state! Up in our constructor, we’ll add our list in the state.
as well as make sure we pass through to props…
One last thing to do before we wrap up and that’s to remove our list items if we don’t want them. So let’s write another handler in App.js to update the list state when an item is removed.
Then we’re updating state and passing in the new list. As you can see we need the onClick handler to pass in an index as a parameter so let’s take care of that next.
Don’t forget to pass ‘this.handleRemove’ into the List component first and then add the ‘itemIndex’ prop onto the ListItem component in the map method.
Then finally add the onClick event handler onto the button in the ListItem component. In order to pass in our index to the event handler, we’re going to use an anonymous function. This prevents the function from firing when the code is first executed and will only fire when it’s clicked on.
Aaaandd finished! I know that was a little long-winded but hopefully, you enjoyed React as much as I do. These steps are one of many ways to do this as usual when it comes to coding so I’d love to hear any alternate takes on the todo list!