#classcomponents
Explore tagged Tumblr posts
Text
React Native Best Practices
What Does it Mean by Best Practices?
It goes in the coding world — there are no strict rules, but some guidelines (more like suggestions) that many coders tend to avoid while writing code. When you’re first starting out, it can be tempting to skip over coding guidelines. After all, your code might work just fine without them. But as your codebase grows bigger, you’ll start to realize that adhering to guidelines is essential for keeping your code healthy and maintainable.
There are several benefits that we have discussed in our Java blog; you can read our blog about the benefits of clean code and best practices.
1. Use TypeScript with Your React Native App
TypeScript is a statically typed programming language which means it requires explicitly defining the data types for variables, functions, and other elements. This not only leads to more reliable code but also helps developers catch bugs during the compilation process.
Consider the following to calculate order pricefunction calculateOrderPrice(order) { return order.price + 1200; }
The current code works fine, but it doesn’t tell us much about what properties the order object contains, which could lead further to a crash if we try to access a property that doesn’t exist.
To prevent the crash and enhance readability, we can use TypeScript. TypeScript is a programming language that adds types to JavaScript. This means that we can specify the type of each property in the object, which will help us avoid errors.interface Order { price: number; name: string; taxPercentage: number; } function calculateOrderPrice(order: Order) { const { price, taxPercentage } = order; const taxValue = price * taxPercentage; return price + taxValue; }
Here is the same function, but now you and your editor are aware of the object properties and their types in code, which makes it easier to extend the functionality.
2. Functional Components over the Class Components
In React Native, you will have two main components: Functional and Class components. But functional components are the way to go in React Native. They’re simpler, more concise, and faster than class components. This makes them easier to read, write, and test. Plus, they can improve your app’s performance.
If you’re not sure what components are, they’re functions that return React elements. So if you’re looking for a way to improve your React Native code, use functional components over class components. They’re the future of React Native development.
Class Component Exampleimport React, { Component } from 'react'; class ClassComponent extends Component { constructor(props) { super(props); this.state = { count: 0, }; } incrementCount = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <View> <Text style={styles.h1}>Class Component</Text> <Text>Count: {this.state.count}</Text> <Button title='Increment' onPress={this.incrementCount}/> </View> ); } } export default ClassComponent;
In this class component example, we’re using the Component class from react to create a component. State is managed within the component’s constructor, and the render method defines the component’s UI.
Functional Component Exampleimport React, { useState } from 'react'; const FunctionalComponent = () => { const [count, setCount] = useState(0); const incrementCount = () => { setCount(count + 1); }; return ( <View> <Text style={styles.h1}>Functional Component</Text> <Text>Count: {count}</Text> <Button title='Increment' onPress={incrementCount}/> </View> ); }; export default FunctionalComponent;
In this functional component example, we’re using the useState hook from react to manage state. The component is defined as a simple JavaScript function that returns JSX to render the UI.
3. Import your dependencies in order
When you have a bunch of imports in one file, it could be a headache trying to find that one specific import you need if you have not organized your imports properly. Therefore it is essential to order imports in a consistent way.
At the same time, you should also ensure that the dependencies have a proper sequence of imports. If the order is not correct, it can affect how components behave and lead to bugs that are hard to find.
Here’s an example of how you can organize your imports:
External imports — react
Internal imports, like relative paths — ../button
In folder imports like ./styles.ts
The imports may be sorted alphabetically in every group
Every group must be divided by white space
import React from 'react'; import { TouchableOpacity, View } from 'react-native'; import { Button, Card } from '../components' import { MainLayout } from '../layouts' import { StyledCard } from './styles.ts'
You can use formatting tools like Eslint and Prettier to automate and enforce the correct import order to avoid such issues.
4. Use Path Alias to avoid long imports
Path aliases are a way to create shorter and more meaningful import paths in your code. This can be helpful when you have a deep or nested folder structure, and it can make your imports easier to read and understand.
For example, instead of writing a long import like this:import { IconButton } from '../../components/buttons'; import { CircleButton } from 'components/buttons'; OR import { CircleButton } from 'buttons';
Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.
Here’s how to use path aliases in both TypeScript and React Native to create shorter and more meaningful import paths in your code.
Path Alias in TypeScript
Create or update the tsconfig.json file in your project if it doesn’t exist already.
Set the baseUrl to . , which represents the root of the directory. This sets the starting point for all path aliases.
Add path aliases to the paths object. In this example, we have two path aliases defined:
// tsconfig.json { "extends": "expo/tsconfig.base", "compilerOptions": { "strict": true, // Path alias config "baseUrl": ".", "paths": { // This needs to be mirrored in babel.config.js // Components is a directory with sub directories "components/*": ["src/components/*"], // We want to expose the exports of the buttons index file "buttons": ["src/components/buttons/index"] } } }
Now, TypeScript will be able to understand and parse the following imports:import { CircleButton } from "components/buttons" import { CircleButton } from "buttons"
2. React Native Path Alias
First, install the babel-plugin-module-resolver as a developer dependencyyarn add - dev babel-plugin-module-resolver npm install babel-plugin-module-resolver - save-dev
Now we can update the babel.config.js file to use the **module-resolver**plugin and point to our directories.**// babel.config.js** module.exports = function (api) { api.cache(true) return { presets: ["babel-preset-expo"], plugins: [ [ "module-resolver", { alias: { // This needs to be mirrored in tsconfig.json components: "./src/components", buttons: "./src/components/buttons", }, }, ], ], } }
Responsive style properties in React refer to the use of functions to create an adaptive user interface or a layout that adjusts to various screen sizes and orientations. Developing a responsive React Native app can be done in multiple ways, and one of them is by using react-native-normalize. This handy library offers functions that help you create responsive layouts effortlessly.
5. Implement Crash Analytics Tools
Crash analytics tools are like your magic tools that keep an eye on your app 24/7. They do real-time monitoring to help you identify crashes and errors. These tools analyze the crash data and give you the lowdown on what’s causing the chaos.
So, if you’re in the development process, and suddenly, the app crashes out of the blue. With the implementation of crash analytics, you can easily find the root causes of these crashes.
There are a bunch of awesome crash analytics tools out there, like Sentry, Firebase, Crashlytics, and more. They’re like your trusty companions, helping you debug and rescue your app from potential crashes.
Read more at https://www.brilworks.com/blog/react-native-best-practices/
#react native#reactnative#react native app development company#react native developers#react native mobile app development
0 notes
Photo

React components In the last slide set of our introduction to React,we discussed react props. Before we can move to react state,I thought it would be wise to to understand components. Components are what makes creating complicated and reusable code a breeze in React.Infact, they are a reason many developers even opt for such libraries and frameworks. In this set,we discuss what components are,the different types we have in react,their differences and more. Enjoy the reading #reactjs #reactcomponents #creatingcomponents #functionalcomponents #classcomponents #statefulandstatelesscomponents #reactprops #reactstate (at Lilongwe, Malawi) https://www.instagram.com/p/B-BWGmiBKt9/?igshid=1fu6vy2kg46lo
#reactjs#reactcomponents#creatingcomponents#functionalcomponents#classcomponents#statefulandstatelesscomponents#reactprops#reactstate
0 notes
Link
lightning:mapコンポーネントの使い方をサンプルソースを使って説明します。 Licensed by Getty ImagesはじめにSalesforceにはGoogleマップを表示するlightning:mapコンポーネントが標準で用意されています。 lightning:mapコンポーネントを使うことで簡単に地図を表示することが可能ですが、できること/できないことがあります。そこで当ブログでは lightning:mapコンポーネント編 Google Maps API編の2回にわたって、Salesforceに地図を表示する方法を紹介します。 今回は、lightning:mapコンポーネントを使って、次のような地図を表示する画面を作成します。サンプルイメージサンプルソース作成するソースコードは次の3つです。 Component Component Controller Apex ClassComponentタグで地図の属性を指定します。 LightningMapExample.cmpタグで使用できる属性は次の通りです。属性内容mapMarkersプロットするマーカーの配列。markersTitleマップリストのタイトル。listViewマップリストの表示:visible/非表示:hidden/自動:auto。showFooterフッター部の表示:true/非表示:false。selectedMarkerValue選択しているマーカーの値。onmarkerselectマーカー選択時のアクション。centerマップの中心位置。zoomLevelマップのズームレベル。デスクトップ:1~22、モバイル:1~20をサポート。Component ControllerCompponent Controllerでは、マーカーの属性を指定します。 ({ init: function (cmp, event, helper) { var action = cmp.get("c.getAccounts"); cmp.set('v.mapMarkers', [{location: {}}]); action.setCallback(this, function(response){ var accounts = response.getReturnValue(); var markers = []; for(var i = 0; i < accounts.length; i++){ var acc = accounts[i]; markers.push({ location: { Country : acc.BillingCountry, State : acc.BillingState, City: acc.BillingCity, Street: acc.BillingStreet }, icon : "standard:account", value: acc.Id, title: acc.Name, description: acc.Description }); } if(markers.length != 0){ cmp.set('v.mapMarkers', markers); } }); $A.enqueueAction(action); }, handlerMarkerSelect: function (cmp, event, helper) { console.log(event.getParam("selectedMarkerValue")); }});LightningMapExampleController.jsinit: functionでマーカー(mapMarkers)を設定する処理を行います。サンプルソースでは、Apex Classから取得した取引先レコードのマーカーを作成しています。 ※注:5行目のcmp.set('v.mapMarkers', [{location: {}}]);によってマーカーの初期値を設定しています。この記述によって表示するマーカーがない場合に、地図が表示されなくなることを防ぎます。 handlerMarkerSelect: functionではマーカークリック時のアクションを定義します。 このサンプルでは、選択したマーカーの値をログ出力しています。マーカー(mapMarkers)の設定で使用できる属性は次の通りです。属性内容iconマップリストに表示するアイコン。locationマーカーの位置情報。緯度経度(Latitude、Longitude)のセットまたは、住所(Country、PostalCode、Country、State、City、Street)のセットを指定する。Streetを指定する場合、Country、PostalCode、Country、State、Cityの1つ以上を合わせて指定する必要がある。titleマーカークリック時に表示される吹き出しのタイトル。descriptionマーカークリック時に表示される吹き出しの内容。valueマーカーの値。マーカークリック時にlightning:mapのselectedMarkerValueに設定される。※icon属性には、Lightning Design Systemのアイコンのみ使用可能 Apex ClassApex Classではマーカーに表示する取引先10件の情報を取得します。 getAccounts(){ return [SELECT Id, Name, BillingCountry, BillingState, BillingCity, BillingStreet, Description FROM Account WHERE BillingCity != NULL AND BillingStreet != NULL LIMIT 10]; }}LightningMapExampleController.apex試しにクエリのLIMITを11とした場合、取得データが11件でもマップに表示されるマーカーは10件です。これは、lightning:mapでは最大10件の住所しかジオコーディングされないからです。 ジオコーディングを行わない(locationを緯度経度で指定した)場合、マーカーは最大100件まで表示することができます。※ジオコーディングの件数には、lightning:mapのcenter属性も含ま���ます。 例えば、マップの中心地点に住所を指定した場合、マーカーに住所を指定できるのは最大9個までとなります。作成結果次のように地図が表示されていれば作成完了です。lightning:mapコンポーネントを利用すると簡単に複数マーカーを立てた地図と、マーカーの一覧を表示する画面を作成することができます。マーカーの一覧にはマーカー名と住所が記載されますが、住所は以下のように「町名・番地、市区郡、都道府県」の形式で表示されてしまいます。 これを「都道府県 市区郡 町名・番地」の形式で表示するためには、以下のように緯度経度と合わせて町名・番地を指定します。町名・番地には、住所に表示したい都道府県+市区郡+町名・番地を設定します。 ※公式でサポートされている指定方法ではないため、使用する際はご注意ください。 location: { Latitude : acc.BillingLatitude, Longitude : acc.BillingLongitude, Street: acc.BillingState + acc.BillingCity + acc.BillingStreet},緯度経度と町名・番地を指定する場合の例緯度経度と町名・番地を指定すると、マーカーの位置は緯度経度が使用され、住所の名称は町名・番地に設定した文字が使用され以下のように表示されます。おわりに最後にlightning:mapコンポーネントでできること/できないことをまとめます。 できること 住所からマーカーを表示(最大10件) 緯度経度からマーカーを表示(最大100件) マーカーのリスト表示 onmarkerselectのイベント処理できないこと 100件を超えるマーカーの表示 マーカーアイコンの変更 onmarkerselect以外のイベント処理次回は、lightning:mapコンポーネントでできないことの対応方法としてGoogleMapsAPIをSalesforceで使用する例を紹介したいと思います。元のページを表示 ≫ 関連する記事Dreamforce2018 day1 Advanced Lightning ComponentsSalesforceからBacklogAPIを利用してみるLightning Data Service を使ってみよう!3倍効率化!? 「Salesforceカレンダー」が超捗るmitocoの魅力Einstein Analytics & Einstein Discoveryで「世界幸福度調査」の結果を分析してみた
0 notes
Video
youtube
ReactJS Tutorials in Hindi | What is Component? | Function and Class Com...
0 notes
Photo

How to set up Vue, StoryBook, and class-components with vue-cli 3.0 ☞ https://medium.com/@javr.llerenas/vue-ts-classcomponents-storybook-with-vue-cli-3-0-b277f717d497 #vuejs #Javascript
0 notes
Photo

How to set up Vue, StoryBook, and class-components with vue-cli 3.0 ☞ https://medium.com/@javr.llerenas/vue-ts-classcomponents-storybook-with-vue-cli-3-0-b277f717d497 #vuejs #Javascript
0 notes
Photo

How to set up Vue, StoryBook, and class-components with vue-cli 3.0 ☞ https://medium.com/@javr.llerenas/vue-ts-classcomponents-storybook-with-vue-cli-3-0-b277f717d497 #vuejs #Javascript
0 notes