My first JS framework - Learning React

React Logo

Background

I started learning React after I finished my freecodecamp FCC. It seems like the obvious choice for multiple reasons. It’s the biggest frontend framework. It has the most jobs available. It is backed by facebook, so it won’t go away any time soon.

I soon realize to learn react, I must learn webpack, babel, es6, blah blah blah. I found out I’m not the only one that who this problem. Luckily, facebook came out with create-react-app, so I don’t have to deal with configuration. (I feature I’ll learn the configuration later)

I’m going to share with you the few must knows about react.

Must knows

Props

React props

React props

Props are information that are passed between components. It is how components communicate. Because of this we can split our webpage into many components, and have one main component(which we call container) to get all the data. Then we can passdown the data to the following props.

In the above example, there is a user component and we can pass props from the parents compoent to the User component(user, desc, and src). Then we can reuse the User component and the User component is completely independent. Note props can also be functions.

State

State is an object that manages the information and on this component. State can store information, the status of the component. For example if we want a component to show or hode such as modal.

1
2
3
4
5
6
7
8
9
10
11
12
13
// state is used to store state of component
this.state = {
modal: false
}
toggle = () => {
this.setState({
modal: !modal,
});
}
...
// modal = true,isOpen
<Modal isOpen={this.state.modal}>
</Modal>
1
2
3
4
5
6
7
8
9

// state can be used to store data.
state = {
modal: false,
album: AlbumJson,
cart: [],
}
...
<Button color="primary" onClick={this.toggle}>Cart({this.state.cart.length})</Button>

Another debugging technique is that I usually type console.log(‘state’, this.state) between return and render to track the state for debugging purpose.

Component life cycle

Component Life Cycle
component life cycle is useful when we want to execute a function when the function state has changed. For example, if want to perform an ajax call before component mounted, we can use the componentWillMount() life cycle and then we can store the data in the state.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import React, { Component } from 'react';

export default class Home extends Component {

componentWillMount(){
// execute api here
}

render() {
return (
<div id="pageHome">
hi this is home page
</div>
);
}
}