How the below React js code formatCount function works?

Jeremy Parker

I'm learning React.js and facing the below confusing code:

import React, { Component } from 'react';
class Counter extends Component {
    state = { 
        counts:1
     };
    render() { 
        return ( 
            <React.Fragment>
                <span>{this.formatCount()}</span>
                <button>Increment</button>
            </React.Fragment>
        );
    }
    formatCount(){
        const {counts} = this.state;
        return counts === 0 ? 'Zero' : counts
    }
}
export default Counter;

A few things confuse me:

1.state is an object rather than a number, but in this line const {counts} = this.state; why assigning an object to a number?

2.Why using {} on counts, but the next line, no {} around counts, return counts === 0 ? 'Zero' : counts?

Tholle

const {counts} = this.state; is called object destructuring and is essentially a shorter way of writing this:

const counts = this.state.counts;

return counts === 0 ? 'Zero' : counts is a use of the ternary operator and can e.g. be used instead of if/else statements like this one:

if (counts === 0) {
  return 'Zero';
} else {
  return counts;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

In javascript how does the below code works

How does the margin works in the below code?

JS function works on console, but not in code

Dynamic tabs for the below code - React js

JS code below works for one <div> and doesn't work for another

How to shorten the flutter dart code below to a function?

What is the input for glTransalatef and glScalef in below Code? How it works?

how to understand below function output for node js

How to pass a function as an argument to other function? My code is given below

How does Lambda function works in this code?

How to implement the header of a function such that the following code works?

how setState in react function component works?

How the below JavaScript Scope works

How not works mix code JS in a Razor View

How React.js return works?

R: How to use apply function in below code instead of loop

How would I be able to implement a shuffled function in the below code?

How does the Python find() function work in below code?

How to make a helper function work - please see code below

Why below .htaccess code not works correctly

How to generate buttons below the dropdown with onSelect on react js?

How to Fix React JS Unused variable like below shown?

Is there something wrong with my code as logic in function works fine in js?

How to create the function below?

React js - calling a function in render works BUT in componentDidMount doesn't

How to export a function in react js?

JS function call works

How recursive animation works in below SVG

How below REGEXP_REPLACE works?