---
# System prepended metadata

title: '2009-GHP-RM-WEB-FT Cookie Jar: Intro to React, Props, State'

---

# 2009-GHP-RM-WEB-FT Cookie Jar: Intro to React, Props, State

## Put your questions in a '##' tag below

## What is ReactDOM.render doing?

It takes the component (React element) we pass as the first argument and renders it into the "supplied container" from the second argument (div element from index.html)

It renders DOM elements backed by instances of their components

[ReactDOM React Documentation](https://reactjs.org/docs/react-dom.html)

## If we are adding event listeners on React, where is the 'event' parameter, if any? Does that object still have the event.target properties?

## Answer

Great question! Consider the code in yesterday's first code demo (first-component)

```javascript=
  addSomething() {
        this.setState({
            message: 'I really like burgers 🍔'
        })
    }
```

This code is in response to adding an event listener in our `render()` method:

```javascript=
<button onClick={this.addSomething}>Click me to change the message</button>
```

Change the code to add the event object


```javascript=
addSomething(event) {
    console.log(event)
    this.setState({
        message: 'I really like burgers 🍔'
    })
}
```

In your dev tools, you'll see:

![](https://i.imgur.com/JluONLq.png)


In conclusion, similar to how we had the event object available to us when we did plain DOM, it's available here because React is just fancier JavaScript! :D


## Below are some frequently asked questions in React:

## Can you walk through what is the purpose of binding 'this' to react methods?

## Answer

Remember: React is like a fancy and extended JavaScript so we have to think about how JavaScript's `this` context works. In your repo, refer to `this` review for more details.

So, let's actually look at what a `class component` looks like:

```javascript=
class SomeComponent extends React.Component {
    constructor() {
        super()
        this.state = {
            someState: 'Some State'
        }
    }
    
    render() { // Render is something we get from React.Component
        <div>{this.state.someState}</div>
    }
}
```

As referenced above, React is fancy and extended JavaScript so above roughly translates to below plain JavaScript class (Note: Below class is extending another class with nothing in it just for demonstration purposes)

```javascript=
class SomeOtherClass {
    someFunction(){...}
}

class SomeClass extends SomeOtherClass {
    constructor() {
        super()
        this.someObject = {
            someStuffInObject: 'Some stuff in object'
        }
    }
    
    someFunction() {
        console.log(this.someObject.someStuffInObject)
    }
}
```

Let's trim the above class a bit to demonstrate the concept of `bind`

```javascript=
class DisplayName {
    constructor(name) {
        this.name = name
    }
    
    display() {
        console.log(this.name)
    }
}
const x = new DisplayName('Noelle')
x.display() // Noelle

// These two lines below simulate a "loss of the `this` context"
// This is synonymous to what we are doing when we do event handling in React
const y = x.display
y() // Uncaught TypeError: Can not ready property name of undefined
```
![](https://i.imgur.com/ekpevTg.png)


So, how do we fix this? By using `.bind` to bind the `this` context to the class


```javascript=
class DisplayName {
    constructor(name) {
        this.name = name
        this.display = this.display.bind(this) // Add this (lol)
    }
    
    display() {
        console.log(this.name)
    }
}

const x = new DisplayName('Noelle')
x.display() // Noelle

// Because we bound the this context to the class, it will refer to name in the class
const y = x.display
y() // Noelle
```

![](https://i.imgur.com/HWMEGeX.png)


## Why do you use this.props for class components and just props for functional components? Does it have to with this[property] syntax for classes?

## Answer

Yup! Please, refer to the question above this. I did an example of a `class component` and its equivalent in just a plain old JavaScript class. For reference, here's how it would look with `functional components`

```javascript=
// Function
const add = (x, y) => {
    return x + y
}
// Call it
add(2, 3)
```

```javascript=
// Functional Component file Add.js
const Add = (props) => {
    return <div>{props.x + props.y}</div>
}

export default Add

// In some other component file called Main.js

import Add from ./Add

const Main = () => {
    // "Call" the add component. We are passing 2 and 3 as props!
    return <Add x={2} y={3} />
}
```


## Why do we use the anonymous function inside the `onClick`?

Because **we are passing a function to be called eventually** instead of calling the function immediately. **We also want to pass an argument to that function being called.** 

If we passed it like this:

```javascript=
onClick={someFunction('hello')}
```

It would immediately run when the component renders, which we don't want

If I create something like this:

```javascript=
const onClick = alert('Hello')
```

It will run automatically

If I create something like this:

```javascript=
const onClick = () => alert('Hello') // Won't immediately run the alert
console.log(onClick) // This will just log the function definition
console.log(onClick()) // This will call the alert function
```

It won't run immediately and will only run when I do line 3. 

Relating back to the `onClick` attribute, we are only trying to invoke the function when a click happens

- [React Documentation: Why is my function being called every time the component renders?](https://reactjs.org/docs/faq-functions.html#why-is-my-function-being-called-every-time-the-component-renders)
- [React Documentation: How do I pass a parameter to an event handler or callback?](https://reactjs.org/docs/faq-functions.html#why-is-my-function-being-called-every-time-the-component-renders)

## I am still confused with REACT, it seems as if its the same process as interacting with the DOM when adding event handlers and listeners

## Answer

We are not doing anything like `.appendChild` or any of the DOM methods. We are giving the component data and it renders that data and then we use `setState` to change that data and the component re-renders

## Follow-up to this ^ Answer so no need to append child, firstchild etc?


## Answer

Nope, none of that needed! You can do some DOM manipulation using some feature of React called [refs](https://reactjs.org/docs/refs-and-the-dom.html) but that's out of scope

## What is the difference between include:[sth] vs include:{include: sth} in eager loading? I have a hard time understand this snippit of code 'const album = await Album.findByPk(req.params.albumId{include:[Artist, {model: Song, include:[Artist]}]})' If there's documentation resource I can read it would be awesome too! ty.

## Answer

Let's break this down together! 

First, 

Think about all the assocations we have:

```javascript=
Song.belongsTo(Album)
Album.hasMany(Song)

Song.belongsTo(Artist)
Artist.hasMany(Song)

Album.belongsTo(Artist)
Artist.hasMany(Album)
```

Secondly, let's take a look at the syntax you are currently looking:

```javascript=
const album = await Album.findByPk(req.params.albumId, {
      include: [Artist, {model: Song, include: [Artist]}]
})
```

If you run this in either Postman or Chrome, you'll get JSON following this format:

```json=
{
    Album Info as an object
    Artist Info as an object
    Song Info in an array of objects
        Artist Info as an object
}
```

Truncating the amount of data being returned for space reasons:

```json=
{
    "id": 2,
    "name": "Zenith",
    "artistId": 1,
    "artist": {
        "id": 1,
        "name": "Dexter Britain"
    },
    "songs": [
        {
            "id": 13,
            "name": "Shooting Star",
            "artistId": 1,
            "artist": {
                "id": 1
                "name": "Dexter Britain"
            }
        }
    ]
}
```

To try to translate this into words:

We are getting the album info with the accompanying artist. We are then getting the list of songs from that album and the artist of the songs

In short: Join Albums with Artists and Songs and join Artists with Songs (refer back to associations)

The one you may be used to seeing:

```javascript=
const album = await Album.findByPk(req.params.albumId, { include: Artist })
```

Can only join one other model

The array syntax includes the models we want to include in an array for multiple models to be loaded

```javascript=
  const album = await Album.findByPk(req.params.albumId, {

      include: [{model: Artist}, {model: Song}]
})
```


Syntax for including all the associated models which functions the same to solution code:

```javascript=
  const album = await Album.findByPk(req.params.albumId, {
    include: { all: true }
})
```

My suggestion is to run all of these in your browser/Postman and see how their results differ


Do message me if this still isn't clear and we can schedule some time to chat!
