Few JavaScript tricks to help you write better React code By Zoranin Tutorials - February 23, 2022 Comments: 0 Views: 531 React is built on top of pure jаvascript, except for a few quirks. This article brings together a few core jаvascript concepts that you will encounter in almost any serious React application. Understanding them will allow you to more confidently work with the library of user interfaces.let and const variablesВ jаvascriptThe let and const keywords make variables more predictable than those declared with var.They have block scope: such variables exist only within the section of code delimited by curly braces. This approach avoids variable conflicts, making the code more predictable.let is used for variables that need to be reassigned after creation. Variables declared with const cannot be reassigned or changed.let greeting; const newUser = true; if (newUser) { // let-variables can be reassigned... greeting = "Nice to meet you!"; } else { greeting = "Welcome back!"; } // ...а const — no newUser = false; // Uncaught TypeError: Assignment to constant variable.В Reactlet and const are the preferred keywords for declaring variables in React because their behavior is predictable. As in JS, variables that are planned to be reassigned are declared with let, and those that do not need to be reassigned are const.const is also used when declaring components in combination with arrow functions, since components remain unchanged.// Function component declared with const (arrow function) const Header = () => { // Local variable declared with const const username = "Bob"; return <Header>Welcome back, {username}!; } Template stringsВ jаvascriptTemplate strings are much more dynamic than the basic String type in JS, obtained using single or double quotes. They make it much easier to interpolate and insert values into strings.It is enough to use the ${} syntax to insert a valid JS expression. You don't need the + operator to concatenate and combine strings, it's easier to write multi-line String objects because you don't need to create newlines with newline (\n) or carriage return (\r).const username = "Fred"; // Code where lines are concatenated with "+" is hard to read const greeting = "Hi " + username + ", how are you?"; // Template strings (``) are much easier to write and read const username = "Anna"; // Dynamic values are inserted using the expression ${} const greeting = `Hi ${username}, how are you?`;В ReactTemplate strings are used to create complex objects of the String class, as well as dynamically calculate element styles depending on conditions. You can insert variable values, operators, function calls, and so on.You can also use nested quotes (single and double) in template strings without fear of errors.function UserCard({ id, name }) { // Parity check for user id... const isOddUser = id % 2 !== 0; // Odd ones get a dark background return <div className={idOddUser ? 'dark-bg' : ''}>{name}</div>} <UserCard id={1} name="Bob" /> // displays a UserCard with a dark backgroundArrow functionsВ jаvascriptWith arrow functions, you can use a shorthand syntax. This makes the entire code shorter. You can replace the return keyword (returns by default if there are no curly braces) and the function body (curly braces) with a big arrow (=>).It is easier to work with objects and classes through the this keyword. You can also remove the parentheses around a single parameter.// Standartnaya funktsiya function capitalize(word) { return word.toUpperCase(); } // Strelochnaya funktsiya const capitalize = (word) => { return word.toUpperCase(); } // Ispol'zuyem vse osobennosti strelochnoy funktsii const capitalize = word => word.toUpperCase(); Show more 263 / 5,000 Translation results // standard function function capitalize(word) { return word.toUpperCase(); } // arrow function const capitalize = (word) => { return word.toUpperCase(); } // Use all the features of the arrow function const capitalize = word => word.toUpperCase(); В ReactIf you can create a standard function in jаvascript, you can create an arrow function. Generally, the second option is preferred because the syntax is simpler.The most common use of arrow functions is to create components, as well as for higher-order array methods such as .map() or .filter().const UserList = ({ users }) => { return ( {users.map((user, index) => ( ))} ); }Default OptionsВ jаvascriptThe default parameter is useful to handle an event passed by a function with no arguments. They also help to avoid errors and make the code more predictable.// No default options function sayHi(name) { return "Hi" + name; } sayHi(); // "Hi undefined" // With default options function sayHi(name = 'Bob') { return "Hi" + name; } sayHi(); // "Hi Bob" // With default parameters and an arrow function const sayHi = (name = 'Jane') => "Hi" + name; sayHi(); // "Hi Jane"В ReactDefault parameters are often used when defining properties. In the example below, we use destructuring assignment to get the 'username' parameter from the properties of an object. Even though the property is not passed, the default value is set to 'guest' and the component still works.const Header = ({ username = "guest" }) => { return <header>Welcome, {username}!</header>; } <Header /> // displays: Welcome, guest! Short conditional statementsВ jаvascriptjаvascript has an abbreviated form for if-else conditional statements - ternary operation (ternary). Unlike if-else, ternary operations are expressions. This gives a lot of flexibility, allowing them to be used just like any other expression (such as ${} in the case of template strings).Ternary operations are not always better than an if-else statement. For example, when processing multiple conditions, the first ones will be unreadable.let age = 26; let greeting; // You can do without the if-else statement in such cases. Here we are just //assign a value to the variable depending on the condition if (age > 18) { greeting = "Hello, fellow adult"; } else { greeting = "Hey kiddo"; } // Ternary operations do the same, but much shorter const greeting = age > 18 ? "Hello, fellow adult" : "Hey kiddo"; greeting; // 'Hello, fellow adult';В ReactYou can output one result through JSX if the condition is true and another if it is false, while writing the code much shorter than if-else.const Navbar = () => { const isAuth = true; return ( <div> // Shows a list of links for logged in users, login screen for others {isAuth? <AuthLinks /> : <Login />} // Show profile only to authorized users {isAuth && <UserProfile/>} </div> ); }Promises + async/awaitВ jаvascriptIt is possible to indefinitely delay the execution of certain sections of jаvascript code (for example, setTimeout(), the listener event, or a network request with the fetch API).Promises are a way to make asynchronous JS code predictable. They help resolve code generated with async. Successfully executed code is handled using the .then() callback functions, errors are handled using the .catch() function;async/await is an improved promise syntax that makes asynchronous code look synchronous.If you want to display the result only if the condition is true, you can use the && operator.// Asynchronous code; 'done' is logged after position data even though 'done' is expected // execute in code later navigator.geolocation.getCurrentPosition(position => { console log(position); }, error => { console.error(error); }); console log("done"); // Asynchronous code processed after the promise; we get the desired result - position data // logged, then logged 'done' const promise = new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject); }); promise .then(position => console.log(position)) .catch(error => console.error(error)) .finally(() => console.log('done')); // Async code with async/await looks like synchronous, most readable way // work with promises async function getPosition() { // async/await only works in functions (for now) const result = await new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject); }); const position = await result; console log(position); console log('done'); } getPosition();В ReactPromises and async/await are used to make network requests such as calling APIs.Libraries like the fetch API or axios use promises for requests that can take an indefinite time to complete. Promises and async/await in similar libraries are also used to generate network requests:// Get data via API using basic promise syntax (note the arrow functions) window.fetch('http://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)); // Get the same data via API with async/await async function getPostData() { const response = await window.fetch('http://jsonplaceholder.typicode.com/posts') // We need to resolve two promises using await to get the final data const data = await response.json(); console log(data); } getPostData();
Why Reactive Programming in Swift? Improving code readability Everyone knows about the nightmarish closures in Swift. Due to the February 20, 2022 Tutorials
How to develop your first app with React Native I want to talk a little about what React Native is, why it is important and popular now, and January 24, 2022 Tutorials
How to quickly write an Android game with Unity At the present time, anyone can become a successful mobile game or application developer without January 9, 2022 Tutorials