Basic React Setup III

This blog will be a continuation of the last two weeks:

Part I, Part II

The whole point of today’s blog is to break out the ability of the app to add a new candy item to a new file. The App.js file is getting very busy, and, as I add new functions, it will become very difficult to read.

This may seem pedantic when the app can only add new candy. However, it is MUCH easier to come back later and figure out what is going on when functions are broken out into different files and organized.

Here is a picture of what the app looks like at the moment, with the backend and frontend running (github for both in the link for Part II, above).

(need to delete the entries for ‘test candy’)

First thing I want to do is make the app.js file less busy by moving the addCandy function to a separate file. To get started, I create new files for AddNewCandy.js and AddNewCandy.css in the src folder.

AddNewCandy.js will need state, so this will be a class component. I’m going to move all of the new candy return to this file from App.js. I also need to bring over several other files, as well as state for newCandy, the handleChange, :

export default class AddNewCandy extends Component{  state = {
newCandy: {
name: "",
origin: "",
price: 1,
image: "",
handleChange = property => event => {
const newCandy = this.state.newCandy
newCandy[property] =
this.setState({ newCandy })
addCandy = event => {
const { name, origin, price, image } = this.state.newCandy
fetch(`${BASE_URL}/candies`, {
method: "POST",
headers: {
"Content-Type": "application/json"
body: JSON.stringify({ name, origin, price, image })
}).then(response => response.json())
.then(candy => {
candies: [...this.state.candies, candy],
newCandy: {
name: "",
origin: "",
price: 0.00,
image: ""
<section className="add-candy">
<h2>Add a Candy</h2>
<form onSubmit={this.addCandy}>
placeholder="image link"
value="Add Candy"

Before going any further, I’m going to change the addCandy function so that it just pulls the candy out of state, and then sends it back up to App.js, all without worrying about the controlled form:

(of course, don’t forget to call it in App.js:

…as well as update the addCandy function:

and finally, move the relevant CSS to the new file created, which associates with the AddNewCandy document:

.add-candy input {
display: block;
width: 100%;
padding: 0.5rem;
margin-bottom: 1rem;
font-family: Roboto, sans-serif;


It’s not a whole lot for one blog, but practicing moving functions from the app file out into other, utility files is really great practice, and lets you leverage some brilliant React functionality. Next week, I’ll cover and integrate functionality to UPDATE and DELETE candies.

Candy Shop Backend GitHub

Candy Shop Frontend GitHub



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store