Basic React Setup Part IV

Benton Westergaard
2 min readSep 7, 2021

Check out parts I, II, and III before following along below.

In the last blog, I went over moving functions from the app.js file to separate files to improve readability.

Before going much further, I want to make the app appear less, well, terrible. One of the first things I notice upon looking at this in it’s current state, is that the ‘new candy’ function takes up a lot of space. Especially if the page is viewed on a mobile device. It makes sense to conditionally render the form so that it only appears when the user clicks a button. So, I’ll tackle this first:

First step is to add a button to the render in App.js.

<button>Click to add a candy</button>

Simple, perhaps a little dated in 2021, but gets the point across. Next, add an onClick and toggle functions (which still need to be written above as functions).

<button onClick={this.toggleAddNewCandy}>Click to add a candy</button>

Now, I add a notice in state, a simple boolean set to false. In other words, unless the button is clicked, the new candy form is not showing:

state = {
candies: [],
isAddNewCandyShowing: false,
}

Now, I format the function toggleAddNewCandy to just change state for isAddNewCandyShowing to it’s opposite.

toggleAddNewCandy = () => {
this.setState({
isAddNewCandyShowing: !this.state.isAddNewCandyShowing
})
}

Finally, I add some additional logic to the return to indicate whether AddNewCandy is showing or not:

{
this.state.isAddNewCandyShowing
? <AddNewCandy addCandy={this.addCandy} />
: null
}

Now, the app will default to the New Candy function NOT showing, but by clicking the new button, it pops up. Since the toggleAddNewCandy function sets status of this component of state to the opposite, clicking the same button will make the form disappear. This is nice, but I should probably also change the button wording to make it syntactically correct whether the form is showing or not, e.g., “Open/Close Add New Candy Form”

Actually, why not use react to create another conditional render, which can change the text depending on whether the form is showing or not!

Basically, I just wrap the button in a conditional which changes the text. Below is just one way of getting this done:

<button onClick={this.toggleAddNewCandy}>
{
this.state.isAddNewCandyShowing
? "Close New Candy Form"
: "Add New Candy"
}
</button>

Learning how to add conditionals to my code was really an ‘aha’ moment in my journey, and forcing myself to build these often — and sometimes with the intention of removing them again/only practicing — dramatically improved my fluidity with writing cohesive, useful code.

There you go. A nice, tidy form which gets out of the way when it isn’t the star of the show.

Front End, Back End

--

--