Cheat Sheet: ReactJS & JavaScript Fundamentals

Cheat Sheet: ReactJS & JavaScript Fundamentals

My Cheat-Sheet for the React Section of the Fullstackopen MOOC by Helsinki University

ยท

4 min read

Introduction

I am doing the Fullstack Open MOOC about fullstack web development provided by Helsinki University. For that, I create summary notes which I can refer back to in future projects. Maybe they are useful to others as well

JavaScript

Variables

There are two types to define variables. With const and with let. The first cannot be changed, the second can. Used like this

const x=5
let y=10

Arrays

Arrays are defined like so:

const arr =[1,2,3,4]

There are several useful methods for its use

  • .forEach(()=>{}) applies the arrow function on each element in the array.

  • .push(x) adds the element x to the original array.

  • .concat(x) creates a new array with the element x appended.

  • .map(()=>{}) creates a new array of elements that are the return values of the arrow function with each respective element of the initial array as input.

Arrays can be destructured like so :const [first, second, ..rest] = arr now first equals 1, second 2 and rest [3,4].

Objects

Objects are defined using curly braces and define key-value-pairs:

const obj = {key1: 1, key2:2}

The values can be accessed with object.key1. For example console.log(obj.key1) would print 1.

You can add keys on the fly using dot notation or square brackets

obj.key3 = 3
obj['key4'] = 4

Functions as object values are object methods. They can access the over properties of the object using the this keyword. Example:

const person = {
    name: "Liz",
    age:25,
    greet: function () {console.log('Hello ', this.name})},
    grow: function () {this.age += 1}
}
person.name // Returns "Liz"
person.greet() //Returns "Hello Liz"
person.grow() // Changes age from 25 to 26

Classes

While there is no class mechanism in JS like in object-oriented programming languages, they can be simulated like so

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
  greet() {
    console.log('hello, my name is ' + this.name)
  }
}

Now the snippet const jason = new Person('Jason', 25) creates a person object.

Functions

Functions can be defined with the function keyword const add = function (a,b) {return a+b} or as arrow functions const add = (a,b) => a+b.

With only a single parameter the parenthesis in the function definition can be omitted.

If the function contains only a single expression, the curly braces around the function body can be omitted.

Initialize a React App

You can set up a react app, my-app with using npm as

npx create-react-app my-app

and start it using npm start.

In the index.js file the line

ReactDOM.createRoot(document.getElementById('root')).render(<App />)

renders the contents of the component <App/> into the div-element with the id 'root' in the public/index.html file.

Components

A component is defined as a JavaScript function that returns the HTML Code like so

const App = () => {
    return (
      <div>
        <p>Hello world</p>
      </div>
    )
};

You can nest components to abstract logic

const Name = (name) => <p>{name}</p>
const Hello = () => (
    <div>
        <h1>Hello</h1>
        <Name name="Max"/>
    </div>
)

Here, the component <Name/> is called in the <Hello/> component and receives a string as a parameter that is dynamically rendered because it is wrapped in curly braces.

For multiple parameters destructuring the input can declutter the component. Its used as such

const Component = ({ variable }) => <div>{variable}</div>

Component Helper Functions

Functions can be added above the component return statement and referenced in the return statement.

Component States

To use states import { useState } from 'react' at the top of the file

Add a state to the component with the useState function call above the component return statement.

const [state, setState] = useState(initialValue)

Now the state can be accessed in the component. For dynamic rendering in the return statement use curly braces.

To update the state to newValueuse the setState(newValue) function.

Now a change of state will trigger a rerender of the component.

The states can be passed to child components. If a state is passed through many components, consider using Redux (not covered here).

Note: Hooks (like useState)must not be called inside a loop, a conditional expression, or any other place that is not a function-defining component. Hooks must always be called in the same order.

Event Handling

Components can react on certain supported Events in the DOM. E.g. an onClick event in a <button>. An event handler is passed to facilitate the response to the event.

These event handlers are functions. So use one of the following ways:

<button onClick={handleEvent}>Button</button>
//or
<button onClick={() => handleEvent()}>Button</button>

Conditional Rendering

One can implement conditional rendering either by using ifstatements in the component with different return values or via dynamic rendering in the returned code. This is used like so

return (
    <div>
        {var && <OtherComponent/>}
    </div>
)

Then the <OtherComponent/> is only rendered when var is truthy.


That concludes the notes for part 1 of the Fullstack Open Mooc. I am learning a ton and have a lot of fun doing it. This post is definitely not enough to learn the concepts, but I hope it will serve as a brief and handy guide for revisiting.

Since I am about halfway through the course, notes for the next sections will follow shortly.

ย