0

I am trying to understand a code written in TypeScript. I myself have a Java background and I find the syntax of the following code hard to understand. The code example is from the first Material UI Select code example:

const [labelWidth, setLabelWidth] = React.useState(0);
React.useEffect(() => {
    setLabelWidth(inputLabel.current!.offsetWidth);
}, []);

So what exaclty is done here? What is the name of the variable const [labelWidt, setLabelWidth]? Are these two variables or is this one variable? Like an array? Later in the code it labelWidth has a number that can be used to set the width of some label. Then setLabelWidth is used like a function that takes a param inputLabel.current!.offsetWidth. Where is it defined that this is a function?

Can someone please explain?

Socrates
  • 8,724
  • 25
  • 66
  • 113
  • 4
    The `const [labelWidth, setLabelWidth] ...` part is called "array destructuring", you can Google it to get a full explanation. In terms of what those 2 variables refer to and where `setLabelWidth` is defined, that relates to the `useState` hook. Looking into "React hooks" will show what's going on (but look up destructuring first so the declaration makes sense). – Jayce444 Jan 23 '20 at 00:10
  • 1
    Read this answer: https://stackoverflow.com/a/47859541/2055998 – PM 77-1 Jan 23 '20 at 00:11
  • Other than the code containing a non-null `!` assertion, the question itself has nothing to do with TypeScript – Patrick Roberts Jan 23 '20 at 03:45
  • @PatrickRoberts TypeScript/JavaScript – Socrates Jan 23 '20 at 21:17

2 Answers2

0

It is an ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network. Destructing

You can also see typescript documentation here

Maclean Pinto
  • 1,075
  • 2
  • 17
  • 39
0

It is destructuring assignment syntax.

Given

const arr = ['item1', 'item2'];

this

const [a, b] = arr;

is the same as

const a = arr[0];
const b = arr[1];
brietsparks
  • 4,776
  • 8
  • 35
  • 69