Episode 49: Refreshing on React (Part 1?)

Written by thatdania | Published 2018/02/06
Tech Story Tags: react | thatdania | refresher | udemy | javascript

TLDRvia the TL;DR App

From ever since I did my final project till now, I conclude that it is impossible to pick up all the concepts of React in two weeks for a final project. The reason I say this is because in a final project, you are focusing on other frameworks such as Express, Node, Mongo or any back end frameworks you are using.

That is not even counting testing and the testing frameworks.

Hence, I’ve decided to take a few steps back in my archeology discovery of code. I have gone back to dig more into React, and properly understand the concepts and the ways of how one writes React.

The challenge of learning how to apply React is not impossible. The challenge of playing around with React to understand what ways in can be written in and how to use them is impossible.

Yes.

Yes I’m looking at you current Seniors at Makers who were trying to use my blog post to setup that MERN framework. You have inspired me to go back to re-learn the stack I once used as it’s finally time.

Note: I wrote that whilst we had to set it up which was a stressful event and that most blog posts about setting up a MERN STACK never gave you the fully functional setup. I apologise if my spacings were incorrect but I can tell you it’s normal to get forms of errors after you set it up.

I tried okay. I tried! I’m part of the cycle. Your computers might have different versions of npm and node!

So, these next few posts are going to vary from concepts of React to my experience of various events (Given that I am currently dividing my time between learning code and events for the moment. You don’t need to hear about the job side of my life. It’s going.)

Nevertheless, let’s get into React!

React. What is it [in short]

No not a reaction. React.

According to ‘Google’ and to my understanding, React was built by Jordan Walke around 2013. He was a developer from Facebook. It is use for front-end development to render out the interfaces and ‘some’ functions of a project. It is a javascript run framework as well, so it’s great if you even know ES5 at this point although conventions are used for ES6.

To get React working, the features React needs are the following:

  • React (dependency, javascript library)
  • React-DOM (Communicates stuff to the page, the Document Object Model, dependency, javascript library)
  • A Bundler (Webpack is recommended at best. It allows you to bundle but also apply some building blocks on the bundle, in case you need extras)
  • A Compiler (Babel is used for compiling Javascript ES6 to ES5 I believe. It works on the code features)
  • A development Server (So you can see stuff on the webpage)

Great.

The concepts of React:

If you haven’t guessed, I am doing a Udemy course on REACT and REDUX. It is literally the most popular one on Udemy. I would recommend Udemy to everyone as they often have discounts and that their courses are rather interactive. Hence, I am using code to show examples from that course.

This is not a promotion. You can go find the course if you want to, when it is on sale. This is just my way of documenting my learning process (Like I have been doing for the past three months or so) and don’t expect me to go through everything (or expect everything.

It’s also very useful if you have done coding before…Javascript, the least.

Good. Let’s go.

It’s very easy to create a React app. The recent one is on their github profile. Just go look at it and follow the steps in dependant of your laptop. It’s basically a command and the name of your project. It will automatically create the project folder for you.

Yes, I’m telling you this so you don’t go make a project folder within a project folder like I have countless times.

How the basic files communicate:

When you create a React app, you will have an index.js and App.js file.

index.js

The index.js renders App.js, as if you have a look at the index.js file, it requires App from app.js (on line 3–4, somewhere there). In App.js, you render the actual javascript ES6. It looks like HTML but it isn’t. This is how the default React page code is placed for it to render on the page.

App. js (The default React page code will be written here. This is an edited file)

If you run this code:

npm start

You will load up a server, with the default React page on.

App.js is where you change the content of your webpage and logic while index.js simply renders the code it’s given onto the page. It’s normal to leave index.js alone.

Note, a big Note: You can call App.js or index.js whatever file names you want as long as you render the right names. They could be anything but for convention, it’s nice to know that you App (is where all the code and logic lies, where all the changes happen) and where Index (is where it renders).

Note, a bigger Note: I always find it helpful to have two terminals running. This is only because when you make a change to your React code, it will automatically respond and show. Whether it is an error or a change, it’s useful to have one terminal running the server whilst the other is where you make your commits to Github.

Components:

App.js is a component and React is build on this idea of Components. A component allows you to isolate and reuse code. You could refer to it as a Class, if you have done coding before. However, what’s interesting about components is that they have lifecycles.

The idea of a lifecycle, is kind of like “hierachy” in which code runs first. There are several methods that you can use that will allow one piece of code to override the other when it’s rendering. It’s like classes, but superclasses.

So, as we developers like to have different classes to have single responsibility rule (I’ll debate about that later), to add a class, we simply make a javascript file (Person.js will be mine) and write a method it in.

import React from 'react'

const person = () => {

return <p> I am a person and I am {Math.floor(Math.random()* 30)} years old</p>

}

export default person;

This is Person.js. It’s all looking crazy at the moment so I’ll point out the things you have to remember.

  • You have to import React into your class, I don’t how to refactor and place it all in one file and call it, but you need that in order to work.
  • Here, I’ve written a method with the arrow function (ES6 syntax) and it is said to have benefits when working with the code word “this” (this, meaning the class). I don’t know why exactly but it is an ES6 feature.
  • Then, let’s say we want to use this class and it’s methods in another file (Say App.js), we thus have to export it, so we can use it in another file.

Props:

Think of props like arguments when passing into a method. For instance,

function myFunction(p1, p2) {return p1 * p2;}

p1 and p2 are arguments, that you pass into a function. Except think of props like a basket of arguments. You can give a function or piece of code a number of arguments and it will all be collated in props, where you can call it based on the argument name.

So first, let’s import the Person.js file into the App.js file on line 4.

import Person from './Person/Person'

And now we can call the Person component in the App component, and let’s give the Person component arguments in the render method, inside the return brackets:

<Person name="Dania" age="21"/>

Yes, with a closing tag for now. Now, in our Person.js, let’s give the function some props and call the props, “name” and “age” as we have written.

import React from 'react'

const person = (props) => {

return <p> I am a {props.name} and I am {props.age} years old</p>

}

export default person;

See, name and age are located in props and we can simply call them by what they are called. How Great is that! But hold up! There’s a slight issue, what if we have this.

<Person name="Maxine" age="3"> Hobbies: Disturb Dania</Person>

Oh no! How are we going to call what’s between the HTMl Tag!

Children

As mentioned earlier, the element in between the HTML tag is called “children” of the parent code. To call children, you simply can do this in Person.js.

import React from 'react'

const person = (props) => {return (<div className="Person">

<p onClick={props.click}> I am {props.name} and I am {props.age} years old</p>  
<p> {props.children}</p>

</div>)

}

export default person;

Now, I’ve put spaces so you can see the code clearly. If we want to return more than one javascript/html like element in React, it needs to be encapsulated in a div so that it is one element being rendered (rather than multiple)

By calling props.children, you are calling what’s in between the HTMl element.

State:

State are like variables when a class is run. It can consist of everything and it’s a state that will always be there. State could be named anything but for convention, it’s good to keep it as state.

state = {person: [{ name:'Dania', age:'23' },{ name:'Maxine', age:'3' },{ name:'Mom', age:'50' }]}

Manipulating the State:

Now, this is where a rule changes. When we want to change a variable’s value, we just say what’s it equal to next. We always will be changing the original value. That isn’t the case, in React. In fact, it is not recommended to change the original state. You always want to make a copy of the state so you have the original in store.

This is where the method this.setState(); comes in. If I have a state which says this:

state = {person: [{ name:'Dania', age:'23' },]}

And I want to change it, by a click method or an event. I would have to write a function that does that for me and then call that function.

switchNameHandler = (newName) => {

this.setState({person: [{ name:’Maxine’, age:’23' },]})

}

Now there’s a very important factor to consider when designing the architecture of React. What remains Stateless and what remains Stateful.

Stateful are files where you define the state in that file. These are called Containers. Stateless is when you have a component that doesn’t deal with the State.

It’s important to keep a minimum level of Stateful components as you don’t want all your files to be changing or affecting your state. States are normally used for events, and if you think about it, you don’t want all your files to have the ability to change those events.

Speaking of, I referred to the SRP (Single Responsibility Rule) earlier and would like to discuss it.

So the App.js is where all my methods and render results are written but contains the state. The Person.js is where I define what is written on the page, and the html elements. This file is Stateless.

It is very subjective in terms of Single Responsibility rule. I believe that in terms of state (which is important) for the context of printing People’s names, that it follows the Rule. It also follows the rule in the sense where all the methods in charge of changing the state is in App.js whilst Person.js is the “printer” printing out people’s names.

Passing methods into each other:

We’ve done the one way, where we have passed Person.js into App.js. What if we want to pass a method of App.js, which changes the state into Person.js.

A way to do it is to simply pass the method as a prop in App.js

render() {return (<div className="App"><Person name={this.state.person[0].name}age= {this.state.person[0].age}click={this.switchNameHandler.bind(this, 'Max!')}/></div>)

As you can see, I have passed a method into the ‘click’ property (this.switchNameHandler) is the method and now what I have to do is bind it. Binding it, then allows the the method to be passed through as a prop. If you don’t bind it, it will remain undefined when it gets called to the other file.

Note: The original syntax is this.switchNameHandler.bind(this) but as you can see, I’ve passed in an argument. You can pass arguments into the bind method! Say if when I click it changes the Person’s name from whatever it was to Max, it will do so!

Two way Binding:

This is an interesting case, as it took me a long time to why we would need to do such a thing. However, let’s take the case.

Let’s say I am changing the person’s name based on the input they type in into the input field. I want to see the original state first and then after state, to see what the name was before and what the name was after. I also want to see when I type in an input, the new name appears depending on what I type

In order to do that, welcome to two way binding.

Let’s make a method that changes the state base on the input in the App.js, as that is the file where our state changes.

nameChangeHandler = (event) => {this.setState({person: [{ name: event.target.value, age:’23' },]})}

You can call the argument anything but for convention sake, let’s call it event. So, why do we call event.target.value?

If you think about the data in the event, it’s not just word or number. It’s a bunch of stuff that we need to pick from, to which data we want printed out.To my understanding, target.value is specifying the targetted (duh) value of the input being typed into the input field.

I may be wrong, please correct me, that’s how I understand it.

Now, if we then make it a property in our render method in our App.js

render() {return (<div className="App"><Person name={this.state.person[0].name}age= {this.state.person[0].age}click={this.switchNameHandler.bind(this, 'Max!')}change={this.nameChangeHandler.bind(this)}/></div>)

And call it in the Person.js (As that’s where the stuff is being printed out, so it knows to print out the input as its typed)

import React from 'react'import './Person.css'

const person = (props) => {return (<div className="Person"><p onClick={props.click}> I am {props.name}and I am {props.age} years old</p><p> {props.children}</p>

<input type="text" onChange={props.change} value={props.name}/>

</div>)}

export default person;

Here, I’ve called the method in an input field so that when someone types in this input field, it prints out the after state. I also have set the value to props.name to show the before state.

Importing CSS files:

This is rather simple and there are two ways you can do this. Either you can do inline styling or seperate styling.

Inline styling is where you write the style code in the same file (say App.js). I find this method quite unclean as there is a way to seperate the file. Not only does it create more lines in your code, but you will sit there you are reading three languages in one file rather than two as you get used to React.

All you have to do is make an App.css file and import it, knowing the file directories.

import './App.css';

How simple is that.

Fun Fact of the Day:

I learnt all these concepts to my understanding in a day, and I have yet to explore them. The best way to learn a new language or software, is doing projects and simply coding whilst following along to a tutorial.

Trust me, Udemy is Great.


Published by HackerNoon on 2018/02/06