I'm starting with react native, and when using a library called react native paper, I've come across a statement where the state is being assigned to a const as shown below.
import * as React from 'react';
import { Searchbar } from 'react-native-paper';
export default class MyComponent extends React.Component {
state = {
firstQuery: '',
};
render() {
const { firstQuery } = this.state;
return (
<Searchbar
placeholder="Search"
onChangeText={query => { this.setState({ firstQuery: query }); }}
value={firstQuery}
/>
);
}
}
Beginning of the 'Render' method, you could see const { firstQuery } = this.state; Could someone please explain why the state is being assigned to a const named 'firstQuery', and even if it have a reason, how will the assignment correctly map the property 'firstQuery' inside the state object to the const ?
Thanks in advance. The code sample is from https://callstack.github.io/react-native-paper/searchbar.html#value
That syntax is not React nor React Native. It's just Javascript's syntax, called destructuring.
const { firstQuery } = this.state;
is equivalent to
const firstQuery = this.state.firstQuery;
just a short-hand shortcut syntax, you see 2 firstQuery
s? People just don't want duplication in code, so they invented it.
See the vanilla javascript snippet below:
const object = {
name: 'Aby',
age: 100,
}
const { name, age } = object;
// instead of
// const name = object.name;
console.log(name, age);
console.log(object.name, object.age);
//=========================================
// imagine:
const obj = {
veryLongPropertyNameToType: 420
}
const { veryLongPropertyNameToType } = obj;
// instead of
// const veryLongPropertyNameToType = obj.veryLongPropertyNameToType;