#100DaysOfCode Day 41: Another Breather to React.js, Updates on Current Condition
React is a library for making Web and Mobile User-Interfaces. It is component driven; everything is a component that is responsible for specific functionality. These small components will then build up and form big components, which becomes the building block of the whole application. This ultimately makes the code more readable and understandable.
Features of React.js includes:
- React uses a Virtual DOM instead of the Real DOM
- The code is readable due to the usage of JSX (JavaScript XML), which basically allows you to write HTML-like code in the JavaScript files
- It also uses SRR (helps in SEO)
ReactJS Virtual DOM
The Virtual DOM is a replication of the Real DOM. The only difference is that a Virtual DOM will not reload the whole component, just those that needed to be updated.
Here is an example of how a Virtual DOM works alongside the Real DOM:
- ReactJS creates a Virtual DOM, which is a replication of the Real DOM
- When data is changed in a component, the entire UI is re-rendered in the virtual DOM alongside the changed data.
- React.js will then compare the changes between the Real DOM and Virtual DOM.
- Once the changes have been specified, the Real DOM will be updated to reflect the changes made in the Virtual DOM.
JSX
In short, here is the difference between rendering User-Interfaces with and without JSX.
With JSX:
class FirstComponent extends React.Component {
render(){
return(
<span className='customSize'>My First Component</span>
);
}
}
Without JSX:
class FirstComponent extends React.Component {
render(){
return(
React.createElement('span', {className: 'customSize'},
);
}
}
Here, you can see that the main advantage to using JSX over non-JSX code is the readability. Of course, the computer could not actually read JSX code, so you will have to transcode it to JavaScript using JSX transformers.
Components
Here is an example of a Component in React:
class MyStatefulComponent extends React.Component {
state = {
title: ''
} componentDidMount(){
console.log("Component Mounted");
} render(){
return(
<div>{this.props.name}</div>;
)
}
}
Before explaining further, it is worth noting what componentDidMount() is.
componentDidMount()
componentDidMount() is a hook that gets invoked right after a React component has been mounted — after the first render() cycle.
Here is an example of a code snippet to explain how componentDidMoutn() works:
class App extends React.Component{
componentDidMount(){
//Runs after the first render() lifecycle
} render(){
console.log("Render Lifecycle");
return <h1>Hello</h1>
}
};
Here is another example with a functional component:
function App(){
React.useEffect(() => {
//Runs after the first render() lifecycle
}, []);
return <h1>Hello</h1>;
}
The next is an example of componentDidMount() running only once:
class App extends React.Component {
state = {
foo: false,
}; componentDidMount(){
console.log("componentDidMount() lifecycle"); //Trigger update
this.setState({foo: !this.state.foo});
} render(){
console.log("Render lifecycle");
return <h1>Hello</h1>
}
};
In this example, React will first render the “Hello” header. Afterwards, once the render cycle ends, the code will trigger the componentDidMount() code cycle and run any code inside said mount.
Here is another example:
class ChildComp extends React.Component {
componentDidMount(){
console.log('componentDidMount() lifecycle');
} render(){
console.log("Render() lifecycle");
return <h1>{this.props.number} times</h1>
}
};class App extends React.Component {
state = {
num = 0;
} handleClick(){
this.setState(state => ({
num: state.num + 1
})); render(){
return(
<div>
<button onClick={this.handleClick.bind(this)}>Increase</button>
<ChildComp number={this.state.num} />
</div>
)
}
};
Try writing the code above in a React environment and see what happens. The console.log("componentDidMount() lifecycle");
should only print once.
However, if I add the following code to <ChildComp number={this.state.num} key={this.state.num} />
then the componentDidMount() method will run twice. This is because by adding the key prop, React will try to find that prop within the component, and force a componentWillUnmonut if the value changes. Next, <ChildComp /> will re-mount and trigger componenetDidMount().
componentDidMount() is useful for API calls. Generally, you should place your API calls in the following positions:
- On an event listener
- If you need to grab initial data when the component mounts, then call it inside componentDidMount()
Other lifecycles such as componentDidUpdate()
, componentWillMount()
, and render()
can be triggered multiple times, which will cause several unnecessary API calls.
componentDidMount(){
fetch('<https://jsonplaceholder.typicode.com/posts>')
.then(res => res.json())
.then(data => this.setState({posts: data}))
.catch(err => console.log(err));
}
You can also use componentDidMount()
with async/await promise-based methods:
async componentDidMount(){
try{
const res = await fetch('<https://jsonplaceholder.typicode.com/posts>');
this.setState({posts: await res.json()})
}catch(e){
console.log(e);
}
}
Components — Continued
There are two ways of writing a component: Class/Stateful/Container Components and Functional/Stateless/Presentational Components.
With its self-explanatory name, a class component is usually used when calling upon a state. Stateful components are components which have a state, which is basicallly a collection of changeable data (call this.setState
inside it) and lifecyle methods (componentDidMount()
, you can call API calls inside).
On the other hand, a Stateless component are components without any state. They are usually used for their presentational value.
Props and States
One of the main features of React is that you can interface with the data inside the components. The two main data that you will interact with is the props and the states.
Props
props
is short for "properties". They represent the property of the component and can be used to pass data to different components. You can also use props to connect the functionalities between a stateless and stateful componen, where the presentational component will render the data to the user interface. Here is an example of a stateful component and stateless component, respectively:
//button.container.js file, a stateful component
import {ButtonView} from './button.presentation'
class MyContainerComponent extends React.Component{
state = {
text: 'Submit'
}
render(){
return(
<ButtonView btnText={this.state.text} />
)
}
}//button.presentation.js file, a stateless component
export const ButtonView = ({btnText}) => {
<div>
<button className="btn btn-info btn-lg">{btnText}</button>
</div>
}
Here, the props
is the the btnText
that resides inside the button.presentation.js
file; in other words, one of the properties for the button is called btnText
, which represents what will be written inside the button.
This property will then be assigned the value of the state within MyContainerComponent
. This is seen in the <ButtonView btnText={this.state.text}/>
line of code. In this case, this is where state
comes in.
State
The main difference between state
and props
is that the former is changeable based on the user-generated event that is happening while the latter is immutable. In short, if you want to have a value that is changeable, then store it inside your component's state
, which represents the object stored inside a component.
Here is another example of a state:
class LoginContainer extends React.Component{
constructor(props){
super(props);
this.state = {
userName: ''
};
} onFillUserName = event => {
this.setState({
userName: event.target.value
});
} render(){
return(
<div>
<input value={this.state.userName} onChange={this.onFillUserName}
</div>
)
}
};
In the code above, we have a component called LoginContainer
. This component has both props and state! The prop is made using the constructor()
method:
constructor(props){
super(props);
this.setState = {
userName: ''
}
}
In JavaScript, super
refers to the parent class constructor (in this case, it points to React.Component
implementation). Without using super
, you would not be able to use the this
constructor. This is because you have not called the parent constructor. When you write down super(props)
, you are calling React.Component
while passing in props
as the argument. Read more here.
Next, we created an event handler called onFillUserName()
. Inside this event handler, there is a this.setState()
method. This is used to change the state of userName
, and is possible because as mentioned before, state
is a mutable object.
Short Update
Hello Cold Brew Lovers! How are you doing? Have you been enjoying today’s Brew? I would like to take this time to give a short update on what’s happening.
Like any other developer, I plan on having my own personal domain name! As of now, I am still figuring out where to host my website and which Content Management System to use. I am currently eyeing WordPress, as it is the quintessential CMS for nearly all websites. However, after going through other choices, I am quite interested in using Ghost or Jekyll.
Aside from that, I am still deciding whether to go for a -.com domain name or use alternatives such as github.io. What are your thoughts on a domain name?
Sources
https://linguinecode.com/post/understanding-react-componentdidmount