Class Component, Event and State

 

1. Components

There are two ways to write React Components.

They are:

  • Functional Components
  • Class Components

1.1 Functional Components

These are JavaScript functions that take props as a parameter if necessary and return react element (JSX).

const Welcome = () => <h1>Hello, User</h1>;
export default Welcome;
JSX

1.2 Class Components

These components are built using an ES6 class.

To define a React Class Component,

  • Create an ES6 class that extends 
    React.Component
    .
  • Add a single empty method to it called 
    render()
    .

1.2.1 extends

The

extends
keyword is used to inherit methods and properties from the
React.Component
.

1.2.2 render()

The

render()
method is the only required method in a class component. It returns the JSX element.

Syntax:

import { Component } from "react";
class MyComponent extends Component {
render() {
return JSX;
}
}
JSX

Use

this.props
in the
render()
body to access the props in a class component.

class Welcome extends Component {
render() {
const { name } = this.props
return <h1>Hello, {name}</h1>
}
}
JSX
Note
The component name should always be in the pascal case.

2. React Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntax differences:

  1. React events are named using camelCase, rather than lowercase.

Example:

HTMLJSX
onclickonClick
onbluronBlur
onchangeonChange
  1. With JSX, you pass a function as the event handler rather than a string.

Example:

<button onclick="activateLasers()">Activate Lasers</button>
HTML
<button onClick={activateLasers}>Activate Lasers</button>
JSX

We should not call the function when we add an event in JSX.

class MyComponent extends Component {
handleClick = () => {
console.log("clicked")
}
render() {
return <button onClick={this.handleClick()}>Click Me</button>
}
}
JSX

In the above function, the

handleClick
is called instead of passed as a reference.

class MyComponent extends Component {
handleClick = () => {
console.log("clicked")
}
render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
JSX

In the above function, the

handleClick
is passed as a reference. So, the function is not being called every time the component renders.

Providing Arrow Functions

To not change the context of

this
, we have to pass an arrow function to the event.

class MyComponent extends Component {
handleClick() {
console.log(this) // undefined
}
render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
JSX
class MyComponent extends Component {
handleClick = () => {
console.log(this) // MyComponent {...}
}
render() {
return <button onClick={this.handleClick}>Click Me</button>
}
}
JSX

3. State

The state is a JS object in which we store the component's data that changes over time.

When the state object changes, the component re-renders.

Intialising State:

class Counter extends Component {
state = { count: 0 }
render() {
const { count } = this.state;
return <p className="count">{count}</p>;
}
}
JSX

3.1 Updating State

We can update the state by using

setState()
. We can provide function/object as an argument to set the state.

Providing Function as an Argument:

Syntax:

this.setState( prevState => ({... }) )

Here the previous state is sent as a parameter to the callback function.

onIncrement = () => {
this.setState((prevState) =>
console.log(`previous state value ${prevState.count}`)
)
}
JAVASCRIPT

3.2 State Updates are Merged

State updates are merged. It means that when you update only one key-value pair in the state object, it will not affect the other key-value pairs in the state object.

// For example let's say your state is as followed:
state = { key1 : value1, key2 : value2 }
// if you use this.setState such as :
this.setState((prevState) => ({ prevState.key1 : value3 }))
// your new state will be :
state = { key1 : value3, key2 : value2 }
JSX

3.3 Functional Components vs Class Components

Functional ComponentsClass Components
Renders the UI based on propsRenders the UI based on props and state

Use Class Components whenever the state is required. Otherwise, use the Functional components.

4. Counter Application

File: src/App.js

import Counter from "./components/Counter";
const App = () => {
return <Counter />
}
export default App;
JSX

File: src/components/Counter/index.js

import { Component } from "react"
import "./index.css"
class Counter extends Component {
state = { count: 0 }
onIncrement = () => {
this.setState((prevState) => ({ count: prevState.count + 1 }))
}
onDecrement = () => {
this.setState((prevState) => ({ count: prevState.count - 1 }))
}
render() {
const { count } = this.state
return (
<div className="container">
<h1 className="count">Count {count}</h1>
<button className="button" onClick={this.onIncrement}>
Increase
</button>
<button className="button" onClick={this.onDecrement}>
Decrease
</button>
</div>
)
}
}
export default Counter
JSX
Collapse
Coding Practice 5
Click Counter

In this project, let's build a Click Counter by applying the concepts we have learned till now.

Refer to the image below:


click counter

Design Files

Click to view

Set Up Instructions

Click to view
  • Download dependencies by running 
    npm install
  • Start up the app using 
    npm start

Completion Instructions

Functionality to be added

The app must have the following functionalities

  • Initially the count of the number of clicks should be 0
  • When Click Me! button is clicked the count of the number of clicks should be incremented by 1
Implementation Files

Use these files to complete the implementation:

  • src/components/ClickCounter/index.js
  • src/components/ClickCounter/index.css

Quick Tips

Click to view
  • You can use the below cursor CSS property for buttons to set the type of mouse cursor, to show when the mouse pointer is over an element,

    cursor: pointer;

    cursor pointer
  • You can use the below outline CSS property for buttons and input elements to remove the highlighting when the elements are clicked,

    outline: none;

Resources

Colors
Hex: #f1f5f8
Hex: #2d3a35
Hex: #c20a72
Hex: #ffffff
Hex: #007bff
Font-families
  • Roboto

Things to Keep in Mind

  • All components you implement should go in the 
    src/components
     directory.
  • Don't change the component folder names as those are the files being imported into the tests.
  • Do not remove the pre-filled code
  • Want to quickly review some of the concepts you’ve been learning? Take a look at the Cheat Sheets.
Speedometer

In this project, let's build a Speedometer by applying the concepts we have learned till now.

Refer to the image below:


speedometer output

Design Files

Click to view

Set Up Instructions

Click to view
  • Download dependencies by running 
    npm install
  • Start up the app using 
    npm start

Completion Instructions

Functionality to be added

The app must have the following functionalities

  • The speed should initially be 0mph

    Here mph means Miles per hour

  • When Accelerate button is clicked,
    • If the speed is less than 200mph, the speed should be increased by 10mph
    • If the speed is equal to 200mph, the speed should not be increased
  • When Apply Brake button is clicked
    • If the speed is greater than 0mph, then the speed should be decreased by 10mph
    • If the speed is equal to 0mph, the speed should not be decreased
Implementation Files

Use these files to complete the implementation:

  • src/components/Speedometer/index.js
  • src/components/Speedometer/index.css

Quick Tips

Click to view
  • You can use the below cursor CSS property for buttons to set the type of mouse cursor, to show when the mouse pointer is over an element,

    cursor: pointer;

    cursor pointer
  • You can use the below outline CSS property for buttons and input elements to remove the highlighting when the elements are clicked,

    outline: none;

Resources

Image URLs
Colors
Hex: #07080c
Hex: #ffffff
Hex: #cbd5e1
Hex: #0b69ff
Hex: #94a3b8
Font-families
  • Roboto

Things to Keep in Mind

  • All components you implement should go in the 
    src/components
     directory.
  • Don't change the component folder names as those are the files being imported into the tests.
  • Do not remove the pre-filled code
  • Want to quickly review some of the concepts you’ve been learning? Take a look at the Cheat Sheets.
Fruits Counter

In this project, let's build a Fruits Counter by applying the concepts we have learned till now.

Refer to the image below:


fruits-counter

Design Files

Click to view

Set Up Instructions

Click to view
  • Download dependencies by running 
    npm install
  • Start up the app using 
    npm start

Completion Instructions

Functionality to be added

The app must have the following functionalities

  • Initially, the count of the eaten mangoes and bananas should be 0
  • When Eat Mango is clicked the count of the mangoes eaten should be incremented by 1
  • When Eat Banana is clicked the count of the bananas eaten should be incremented by 1
Implementation Files

Use these files to complete the implementation:

  • src/components/FruitsCounter/index.js
  • src/components/FruitsCounter/index.css

Quick Tips

Click to view
  • State updates are merged. It means that when you update only one key-value pair in the

    state
    object, it will not affect the other key-value pairs in the state object.

    For example let's say your state is as followed:

    state = { key1 : value1, key2 : value2 }

    If you use this.setState such as :

    this.setState(prevState => ({key1: prevState + valueN}))

    Your new state will be :

    state = { key1 : value3, key2 : value2 }
  • You can use the below cursor CSS property for buttons to set the type of mouse cursor, to show when the mouse pointer is over an element,

    cursor: pointer;

    cursor pointer
  • You can use the below outline CSS property for buttons and input elements to remove the highlighting when the elements are clicked,

    outline: none;

Resources

Image URLs
Colors
Hex: #ffd569
Hex: #ffffff
Hex: #000000
Hex: #007bff
Font-families
  • Roboto

Things to Keep in Mind

  • All components you implement should go in the 
    src/components
     directory.
  • Don't change the component folder names as those are the files being imported into the tests.
  • Do not remove the pre-filled code
  • Want to quickly review some of the concepts you’ve been learning? Take a look at the Cheat Sheets.

Post a Comment

Please Select Embedded Mode To Show The Comment System.*

Previous Post Next Post

Contact Form