Learn React: Add Event Functionality to a Component

Welcome to the third installment of our learning React.js tutorial series (Part 1), (Part 2). Here’s a link to the GitHub Repo. The Read Me has all the instructions needed to get started plus some helpful links for anyone unfamiliar with GitHub. There is a concept in React that state is immutable. This doesn’t mean state can’t be changed. It just means we don’t mutate state directly. We do it with outside functions and copies.

The rule of thumb in React is to modify state via a setState function rather than mutate state directly. For example, our state is an array so rather than writing something like this.state.taks.push(insert new item here) our function will look a lot different and utilize setState.

It’s possible to update state with the push method directly, I believe there are use cases where it provides update functionality but it causes bugs along the component tree and I don’t recommend it. Here are some excellent resources for a deeper dive into setState from Kingsley Silas and one from Geeks for Geeks.

In this article, we are going to build a new React.js component, SubmitComponent, and add event functionality — to add text through the text bar. (We won’t discuss the JavaScript Event handlers themselves in depth so please check out this article instead if you’re curious.)

Setting up Our App for the New Code In index.js (from the Github folder) , please make sure that your index.js looks like the image below:

Please update TaskComponent as well to look like this: For more information check this popular resource.