React Episode 1

If you’re not sure about what React is, check out my first tutorial: https://geekladysite.wordpress.com/2020/09/01/react-episode-0/

The following content is based on Mosh’s tutorial and some are supplemented materials. Strongly recommend his tutorial!

In this blog, I’ll show you how to create components! Let’s get started!

But before that, let me introduce a handy tool if you use Visual Studio Code as IDE. Go to extension tab, find Simple React Snippets, install it.

Fig 1.Simple React Snippets

This helps our productivity in writing React. You simply type some keywords and this extension will automatically write some code!

Create a file with extension ‘.jsx’ or ‘.js’. Before React adopts Babel compiler, .jsx was used but now both are acceptable. We can type imr to import React and cc to create a component template. Here is what you will see.

Fig 2. component

So what are we building? We will build a component which displays a number and has a button to increment the number. Before we assign any value, we can create such a skeleton.

Fig 3. Wrong code!

Why is this wrong? Because in last episode, we know JSX calls React.createElement() method. In this case, it doesn’t know which element to create. To solve this problem, we put a parent element on top of these two tags.

Fig 4. Right code!

Let’s firstly hard code values.

Fig 5. add value
Fig 6. Effect
Fig 7. Show state’s current value

Now let’s add a property in state and use that expression. Be aware that expression is wrapped in {}.

Are you curious why we use this.state rather than state?

this represents the current object.

All right, let’s twist the UI of this number. If it’s zero, the screen will show ‘zero’ word rather than ‘0’. We can define formatCount method and use it in render.

Fig 8. Change UI

const { count } = this.state; uses destructuring assignment.

Check out this document for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Leave a comment