React Native - Striver Technosoft http://www.strivertech.com Agile Organization | Top Web and Mobile Development Solution Thu, 18 Apr 2024 05:29:23 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 http://www.strivertech.com/wp-content/uploads/2022/04/cropped-cropped-Striver-Technology-2-32x32.png React Native - Striver Technosoft http://www.strivertech.com 32 32 React keys fully explained! http://www.strivertech.com/react-keys-fully-explained/?utm_source=rss&utm_medium=rss&utm_campaign=react-keys-fully-explained Thu, 18 Apr 2024 05:22:29 +0000 https://www.strivertech.com/?p=7005 React keys fully explained! Discover the power of React keys with our detailed explanation. Learn how to effectively use keys to optimize performance and manage component state. Keys in React When mapping over an array of elements in React, you need to provide a key prop to each element. If you don’t, React will throw […]

The post React keys fully explained! first appeared on Striver Technosoft.

]]>

React keys fully explained!

Discover the power of React keys with our detailed explanation. Learn how to effectively use keys to optimize performance and manage component state.

Keys in React

When mapping over an array of elements in React, you need to provide a key prop to each element. If you don’t, React will throw a warning in the console.

  • What should we use as a key?

  • What happens if we don’t provide a key?

  • So why do we need to provide a key prop?

Problematic code

Let’s look at some code where React throws a warning because we didn’t provide a key prop:

function App() {
  const items = ["apple", "banana", "cherry"];

  return (
    <ul>
      {items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  );
}

This code will throw a warning in the console:

Warning: Each child in a list should have a unique "key" prop.

What’s the problem?

When you map over an array of elements, React needs a way to identify each element uniquely.

Imagine the files on your computer didn’t have a name. They were identified only by their order. If you moved a file to a different position or deleted a file, you wouldn’t know which file you were referring to. This is an analogy coming from React’s own documentation.

React needs a way to always know which element is which. That’s why you need to provide a key prop.

Rules

Two rules to follow when choosing a key:

  1. Stable: The key should be stable. It shouldn’t change between renders.

  2. Unique: The key should be unique among siblings.

It’s also why you shouldn’t use the index as a key. If the order of the elements changes, React won’t be able to identify which element is which.

Solution

Let’s fix the warning by providing a key prop:

function App() {
  const items = ["apple", "banana", "cherry"];

  return (
    <ul>
      {items.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

In this case, it’s ok to use the item itself as a key because the items are unique.

In other cases where you get data from backend, you’ll likely want to use id or some other unique identifier instead of the item itself.

Surprise, it’s not a prop

The key prop is not an actual prop that gets passed to the component. It’s a special attribute that React uses internally to keep track of elements. That’s why you can’t access the key prop inside the component.

If we look at the JSX from the previous example again:

function App() {
  const items = ["apple", "banana", "cherry"];

  return (
    <ul>
      {items.map((item) => (
        <li key={item}>{item}</li>
      ))}
    </ul>
  );
}

When this JSX is transpiled, it will look something like this:

const element = {
  type: "ul",
  props: {
    children: [
      {
        type: "li",
        key: "apple",
        props: {
          children: "apple",
        },
      },
      {
        type: "li",
        key: "banana",
        props: {
          children: "banana",
        },
      },
      {
        type: "li",
        key: "cherry",
        props: {
          children: "cherry",
        },
      },
    ],
  },
};

As you can see, the key is a top-level property of the element, not a prop that gets passed to the component. React uses this key to identify the element internally and keep track of it across re-renders.

So remember, when mapping over an array of elements in React, always provide a unique and stable key to each element. It’s not a prop, but a special attribute that React uses under the hood to efficiently update the DOM.

The post React keys fully explained! first appeared on Striver Technosoft.

]]>
Quickstart: Get started with Gemini using the REST API http://www.strivertech.com/rest_quickstart/?utm_source=rss&utm_medium=rss&utm_campaign=rest_quickstart Tue, 27 Feb 2024 05:55:15 +0000 https://www.strivertech.com/?p=6982 Quickstart: Get started with Gemini using the REST API with React Native https://www.strivertech.com/wp-content/uploads/2024/02/gemin.mp4 Greetings, developers! Today, we embark on an exciting journey to seamlessly integrate Gemini with REST API in your React Native applications. Inspired by Google’s REST API Quickstart, this step-by-step guide aims to empower you with enhanced testing capabilities and a streamlined development […]

The post Quickstart: Get started with Gemini using the REST API first appeared on Striver Technosoft.

]]>

Quickstart: Get started with Gemini using the REST API with React Native

Greetings, developers! Today, we embark on an exciting journey to seamlessly integrate Gemini with REST API in your React Native applications. Inspired by Google’s REST API Quickstart, this step-by-step guide aims to empower you with enhanced testing capabilities and a streamlined development process.

If you want to quickly try out the Gemini API, you can use curl commands to call the methods in the REST API. The examples in this tutorial show calls for each API method.

The Colab uses Python code to set an environment variable and to display an image, but you don’t need Colab to work with the REST API. You should be able to run all of the curl examples outside of Colab, without modification, as long as you have API_KEY set as described in the next section.

For each curl command, you must specify the applicable model name and your API key.

Ensure you have the following prerequisites ready before diving into the integration:

  • A React Native project set up
  • Access to Gemini’s REST API (credentials and endpoint)

To use the Gemini API, you’ll need an API key. If you don’t already have one, create a key in Google AI Studio.

In Colab, add the key to the secrets manager under the “🔑” in the left panel. Give it the name API_KEY. You can then add it as an environment variable to pass the key in your curl call.

In a terminal, you can just run API_KEY="Your API Key".

 
import os
from google.colab import userdata

os
.environ['API_KEY'] = userdata.get('API_KEY')

Use the generateContent method to generate a response from the model given an input message. If the input contains only text, use the gemini-pro model.

 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[{
          "text": "Write a story about a magic backpack."}]}]}' 2> /dev/null
 
{
  "candidates": [
    {
      "content": {
        "parts": [
          {
            "text": "Once upon a time, in a small town nestled at the foot of towering mountains, there lived a young girl named Lily. Lily was an adventurous and imaginative child, always dreaming of exploring the world beyond her home. One day, while wandering through the attic of her grandmother's house, she stumbled upon a dusty old backpack tucked away in a forgotten corner. Intrigued, Lily opened the backpack and discovered that it was an enchanted one. Little did she know that this magical backpack would change her life forever.\n\nAs Lily touched the backpack, it shimmered with an otherworldly light. She reached inside and pulled out a map that seemed to shift and change before her eyes, revealing hidden paths and distant lands. Curiosity tugged at her heart, and without hesitation, Lily shouldered the backpack and embarked on her first adventure.\n\nWith each step she took, the backpack adjusted to her needs. When the path grew treacherous, the backpack transformed into sturdy hiking boots, providing her with the confidence to navigate rocky terrains. When a sudden rainstorm poured down, the backpack transformed into a cozy shelter, shielding her from the elements.\n\nAs days turned into weeks, Lily's journey took her through lush forests, across treacherous rivers, and to the summits of towering mountains. The backpack became her loyal companion, guiding her along the way, offering comfort, protection, and inspiration.\n\nAmong her many adventures, Lily encountered a lost fawn that she gently carried in the backpack's transformed cradle. She helped a friendly giant navigate a dense fog by using the backpack's built-in compass. And when faced with a raging river, the backpack magically transformed into a sturdy raft, transporting her safely to the other side.\n\nThrough her travels, Lily discovered the true power of the magic backpack. It wasn't just a magical object but a reflection of her own boundless imagination and tenacity. She realized that the world was hers to explore, and the backpack was a tool to help her reach her full potential.\n\nAs Lily returned home, enriched by her adventures and brimming with stories, she decided to share the magic of the backpack with others. She organized a special adventure club, where children could embark on their own extraordinary journeys using the backpack's transformative powers. Together, they explored hidden worlds, learned valuable lessons, and formed lifelong friendships.\n\nAnd so, the legend of the magic backpack lived on, passed down from generation to generation. It became a reminder that even the simplest objects can hold extraordinary power when combined with imagination, courage, and a sprinkle of magic."
          }
        ],
        "role": "model"
      },
      "finishReason": "STOP",
      "index": 0,
      "safetyRatings": [
        {
          "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_HATE_SPEECH",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_HARASSMENT",
          "probability": "NEGLIGIBLE"
        },
        {
          "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
          "probability": "NEGLIGIBLE"
        }
      ]
    }
  ],
  "promptFeedback": {
    "safetyRatings": [
      {
        "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HATE_SPEECH",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_HARASSMENT",
        "probability": "NEGLIGIBLE"
      },
      {
        "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
        "probability": "NEGLIGIBLE"
      }
    ]
  }
}

If the input contains both text and image, use the gemini-pro-vision model. The following snippets help you build a request and send it to the REST API.

 
curl -o image.jpg https://storage.googleapis.com/generativeai-downloads/images/scones.jpg
 
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  385k  100  385k    0     0  2053k      0 --:--:-- --:--:-- --:--:-- 2050k
 
import PIL.Image

img
= PIL.Image.open("image.jpg")
img
.resize((512, int(img.height*512/img.width)))

png

 
echo '{
  "contents":[
    {
      "parts":[
        {"text": "What is this picture?"},
        {
          "inline_data": {
            "mime_type":"image/jpeg",
            "data": "'$(base64 -w0 image.jpg)'"
          }
        }
      ]
    }
  ]
}' > request.json
 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro-vision:generateContent?key=${API_KEY} \
        -H 'Content-Type: application/json' \
        -d @request.json 2> /dev/null | grep "text"
 
"text": " The picture shows a table with a white tablecloth. On the table are two cups of coffee, a bowl of blueberries, and a plate of scones. There are also some flowers on the table."

Using Gemini, you can build freeform conversations across multiple turns.

 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Write the first line of a story about a magic backpack."}]},
        {"role": "model",
         "parts":[{
           "text": "In the bustling city of Meadow brook, lived a young girl named Sophie. She was a bright and curious soul with an imaginative mind."}]},
        {"role": "user",
         "parts":[{
           "text": "Can you set it in a quiet village in 1600s France?"}]},
      ]
    }' 2> /dev/null | grep "text"
 
"text": "In the quaint village of Fleur-de-Lys, nestled amidst the rolling hills of 17th century France, lived a young maiden named Antoinette. She possessed a heart brimming with curiosity and a spirit as vibrant as the wildflowers that bloomed in the meadows.\n\nOne sunny morn, as Antoinette strolled through the cobblestone streets, her gaze fell upon a peculiar sight—a weathered leather backpack resting atop a mossy stone bench. Intrigued, she cautiously approached the bag, her fingers tracing the intricate carvings etched into its surface. As her fingertips grazed the worn leather, a surge of warmth coursed through her body, and the backpack began to emit a soft, ethereal glow."

Every prompt you send to the model includes parameter values that control how the model generates a response. The model can generate different results for different parameter values. Learn more about model parameters.

Also, you can use safety settings to adjust the likelihood of getting responses that may be considered harmful. By default, safety settings block content with medium and/or high probability of being unsafe content across all dimensions. Learn more about safety settings.

The following example specifies values for all the parameters of the generateContent method.

 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "contents": [{
            "parts":[
                {"text": "Write a story about a magic backpack."}
            ]
        }],
        "safetySettings": [
            {
                "category": "HARM_CATEGORY_DANGEROUS_CONTENT",
                "threshold": "BLOCK_ONLY_HIGH"
            }
        ],
        "generationConfig": {
            "stopSequences": [
                "Title"
            ],
            "temperature": 1.0,
            "maxOutputTokens": 800,
            "topP": 0.8,
            "topK": 10
        }
    }'  2> /dev/null | grep "text"
 
"text": "Once upon a time, in a small town nestled at the foot of a majestic mountain range, lived a young girl named Lily. Lily was a bright and curious child who loved to explore the world around her. One day, while playing in the forest near her home, she stumbled upon a hidden cave. Intrigued, she stepped inside, and to her amazement, she discovered a dusty old backpack lying in a corner.\n\nCuriosity piqued, Lily reached out and picked up the backpack. As soon as her fingers brushed against the worn leather, she felt a strange tingling sensation coursing through her body. Suddenly, the backpack began to glow, emitting a soft, ethereal light that filled the cave.\n\nWith wide-eyed wonder, Lily opened the backpack to find it filled with an assortment of magical objects. There was a compass that always pointed to the nearest adventure, a magnifying glass that could reveal hidden secrets, a telescope that allowed her to see distant lands, and a book that contained the knowledge of the universe.\n\nOverjoyed with her discovery, Lily took the magic backpack home and began using its contents to explore the world in ways she had never imagined. She followed the compass to discover hidden treasures, used the magnifying glass to uncover the secrets of nature, gazed through the telescope to witness the wonders of the cosmos, and delved into the book to learn about the mysteries of the universe.\n\nAs Lily's adventures continued, she realized that the magic backpack was more than just a collection of enchanted items. It was a symbol of her own limitless potential and the power of her imagination. It taught her that with curiosity, courage, and a touch of magic, anything was possible.\n\nNews of Lily's magical backpack spread throughout the town, and soon, children from all around came to her, eager to learn about its wonders. Lily welcomed them with open arms, sharing her stories and inspiring them to embark on their own adventures.\n\nAnd so, the magic backpack became a beacon of hope and wonder, reminding everyone that the world is full of hidden treasures waiting to be discovered, if only one has the courage to step into the unknown."

By default, the model returns a response after completing the entire generation process. You can achieve faster interactions by not waiting for the entire result, and instead use streaming to handle partial results.

 
!curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:streamGenerateContent?key=${API_KEY} \
       
-H 'Content-Type: application/json' \
       
--no-buffer \
       
-d '{ "contents":[{"parts":[{"text": "Write long a story about a magic backpack."}]}]}' \
       
2> /dev/null | grep "text"
 
"text": "In the bustling city of Meadow brook, lived a young girl named Sophia with an"
            "text": " insatiable curiosity that knew no bounds. One sunny morning, as she walked to school, she came across a charming little shop tucked away on a side street. Int"
            "text": "rigued, she stepped inside and was immediately captivated by the mystical aura that enveloped the room. Amidst the shelves lined with ancient books and curious trinkets, she stumbled upon a peculiar backpack. Crafted from deep emerald leather and adorned with shimmering crystals, it seemed to pulse with a hidden energy. Unable to resist its allure"
            "text": ", Sophia reached out and touched the backpack, and in that moment, a powerful connection was forged. As if awakening from a long slumber, the backpack emitted a soft glow, revealing its extraordinary properties.\n\nSophia discovered that this was no ordinary backpack. It possessed the magical ability to grant her wishes, but only if they were made with a pure heart and genuine intentions. Overwhelmed with excitement and responsibility, Sophia pondered deeply about how she would use this extraordinary gift. She decided that her first wish would be to make her grandmother, who lived far away, feel close to her. With a heartfelt desire, she whispered her wish to the backpack"

When using long prompts, it might be useful to count tokens before sending any content to the model.

 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:countTokens?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[{
          "text": "Write a story about a magic backpack."}]}]}' > response.json
 
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   127    0    23  100   104    105    477 --:--:-- --:--:-- --:--:--   585
 
cat response.json
 
{
  "totalTokens": 8
}

Embedding is a technique used to represent information as a list of floating point numbers in an array. With Gemini, you can represent text (words, sentences, and blocks of text) in a vectorized form, making it easier to compare and contrast embeddings. For example, two texts that share a similar subject matter or sentiment should have similar embeddings, which can be identified through mathematical comparison techniques such as cosine similarity.

Use the embedding-001 model with either embedContents or batchEmbedContents:

 
curl https://generativelanguage.googleapis.com/v1beta/models/embedding-001:embedContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
        "model": "models/embedding-001",
        "content": {
        "parts":[{
          "text": "Write a story about a magic backpack."}]} }' 2> /dev/null | head
 
{
  "embedding": {
    "values": [
      0.008624583,
      -0.030451821,
      -0.042496547,
      -0.029230341,
      0.05486475,
      0.006694871,
      0.004025645,
 
curl https://generativelanguage.googleapis.com/v1beta/models/embedding-001:batchEmbedContents?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "requests": [{
        "model": "models/embedding-001",
        "content": {
        "parts":[{
          "text": "Write a story about a magic backpack."}]} }]}' 2> /dev/null | head
 
{
  "embeddings": [
    {
      "values": [
        0.008624583,
        -0.030451821,
        -0.042496547,
        -0.029230341,
        0.05486475,
        0.006694871,

If you GET a model’s URL, the API uses the get method to return information about that model such as version, display name, input token limit, etc.

 
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-pro?key=$API_KEY
 
{
  "name": "models/gemini-pro",
  "version": "001",
  "displayName": "Gemini Pro",
  "description": "The best model for scaling across a wide range of tasks",
  "inputTokenLimit": 30720,
  "outputTokenLimit": 2048,
  "supportedGenerationMethods": [
    "generateContent",
    "countTokens"
  ],
  "temperature": 0.9,
  "topP": 1,
  "topK": 1
}

If you GET the models directory, it uses the list method to list all of the models available through the API, including both the Gemini and PaLM family models.

 
curl https://generativelanguage.googleapis.com/v1beta/models?key=$API_KEY
 
{
  "models": [
    {
      "name": "models/chat-bison-001",
      "version": "001",
      "displayName": "Chat Bison",
      "description": "Chat-optimized generative language model.",
      "inputTokenLimit": 4096,
      "outputTokenLimit": 1024,
      "supportedGenerationMethods": [
        "generateMessage",
        "countMessageTokens"
      ],
      "temperature": 0.25,
      "topP": 0.95,
      "topK": 40
    },
    {
      "name": "models/text-bison-001",
      "version": "001",
      "displayName": "Text Bison",
      "description": "Model targeted for text generation.",
      "inputTokenLimit": 8196,
      "outputTokenLimit": 1024,
      "supportedGenerationMethods": [
        "generateText",
        "countTextTokens",
        "createTunedTextModel"
      ],
      "temperature": 0.7,
      "topP": 0.95,
      "topK": 40
    },
    {
      "name": "models/embedding-gecko-001",
      "version": "001",
      "displayName": "Embedding Gecko",
      "description": "Obtain a distributed representation of a text.",
      "inputTokenLimit": 1024,
      "outputTokenLimit": 1,
      "supportedGenerationMethods": [
        "embedText",
        "countTextTokens"
      ]
    },
    {
      "name": "models/embedding-gecko-002",
      "version": "002",
      "displayName": "Embedding Gecko 002",
      "description": "Obtain a distributed representation of a text.",
      "inputTokenLimit": 2048,
      "outputTokenLimit": 1,
      "supportedGenerationMethods": [
        "embedText",
        "countTextTokens"
      ]
    },
    {
      "name": "models/gemini-pro",
      "version": "001",
      "displayName": "Gemini Pro",
      "description": "The best model for scaling across a wide range of tasks",
      "inputTokenLimit": 30720,
      "outputTokenLimit": 2048,
      "supportedGenerationMethods": [
        "generateContent",
        "countTokens"
      ],
      "temperature": 0.9,
      "topP": 1,
      "topK": 1
    },
    {
      "name": "models/gemini-pro-vision",
      "version": "001",
      "displayName": "Gemini Pro Vision",
      "description": "The best image understanding model to handle a broad range of applications",
      "inputTokenLimit": 12288,
      "outputTokenLimit": 4096,
      "supportedGenerationMethods": [
        "generateContent",
        "countTokens"
      ],
      "temperature": 0.4,
      "topP": 1,
      "topK": 32
    },
    {
      "name": "models/gemini-ultra",
      "version": "001",
      "displayName": "Gemini Ultra",
      "description": "The most capable model for highly complex tasks",
      "inputTokenLimit": 30720,
      "outputTokenLimit": 2048,
      "supportedGenerationMethods": [
        "generateContent",
        "countTokens"
      ],
      "temperature": 0.9,
      "topP": 1,
      "topK": 32
    },
    {
      "name": "models/embedding-001",
      "version": "001",
      "displayName": "Embedding 001",
      "description": "Obtain a distributed representation of a text.",
      "inputTokenLimit": 2048,
      "outputTokenLimit": 1,
      "supportedGenerationMethods": [
        "embedContent",
        "countTextTokens"
      ]
    },
    {
      "name": "models/aqa",
      "version": "001",
      "displayName": "Model that performs Attributed Question Answering.",
      "description": "Model trained to return answers to questions that are grounded in provided sources, along with estimating answerable probability.",
      "inputTokenLimit": 7168,
      "outputTokenLimit": 1024,
      "supportedGenerationMethods": [
        "generateAnswer"
      ],
      "temperature": 0.2,
      "topP": 1,
      "topK": 40
    }
  ]
}

The post Quickstart: Get started with Gemini using the REST API first appeared on Striver Technosoft.

]]>
Are bugs and slow delivery ok? http://www.strivertech.com/are-bugs-and-slow-delivery-ok/?utm_source=rss&utm_medium=rss&utm_campaign=are-bugs-and-slow-delivery-ok Thu, 01 Feb 2024 06:52:32 +0000 https://www.strivertech.com/?p=6949 Are bugs and slow delivery ok? The majority of the IT industry operates with low-quality development and survives. However, there are companies where quality is not an option. High quality is NOT for everyone. Does it make sense for your company? We’ve compiled a checklist of questions to find out the answer. 95% of companies […]

The post Are bugs and slow delivery ok? first appeared on Striver Technosoft.

]]>

Are bugs and slow delivery ok?

The majority of the IT industry operates with low-quality development and survives. However, there are companies where quality is not an option.

High quality is NOT for everyone.

Does it make sense for your company?

We’ve compiled a checklist of questions to find out the answer.

Navigating the Quality Quandary: The Impact of Bugs and Slow Delivery

95% of companies can survive with low quality

Quality standards in the software development industry are generally quite low. Quality is a nice-to-have, something on the wishlist. But quality is not a must-have. The following are some symptoms that you don’t need high quality:

  • Bugs are ok. When a bug occurs, the impact is small. There isn’t any major financial loss no reputation loss no legal/regulatory risk.

  • Slow bug fix delivery is ok. If the bug fix gets delivered in a week or month, it doesn’t matter that much. It can wait. There isn’t much of a loss.

  • Slow feature delivery is ok. It doesn’t matter if new features are delivered rarely. Business complains and wants faster, but they accept the slowness.

  • Wasting time is ok. Developers spend most of their day manually debugging the code and fixing regression bugs – it’s ok.

  • Burnout is ok. The team is working overtime, facing stress and health problems. Delivery is unsustainable. More mistakes are made. But, it’s ok. When the team gets burned out, the developers can be replaced.

5% of companies can NOT compromise on quality

The following are some industries where high-quality standards are NOT optional. Quality is not a choice. Examples include:
 
  • Financial Services & Payments Processing

  • Manufacturing & Industrial Automation

  • Logistics, Warehouse & Retail

What’s the impact:

  • Bugs are NOT ok. Even one bug has a high cost. The cost may involve financial losses, and reputation losses – leading to loss of customers, hence revenue loss as well as lawsuits.

  • Slow bug fix delivery is NOT ok. In case a bug is discovered in production, the customer expects a fix ASAP. Every minute that passes by is costly.

  • Slow feature delivery is NOT ok. The market is competitive. When the business has high-priority features, they don’t want to wait for months to release.

  • Wasting time is NOT ok. The company does not want the team to do repetitive manual work. It is unacceptable to spend most of the day debugging and fixing regression bugs when that could be prevented through automated tests.

  • Burnout is NOT ok. The company’s product is so critical, that sustainable delivery must be ensured. Heroism and firefighting are not an option.

Should you invest in software quality?

For 95% of companies, the answer is: No.

These companies survive fine with low quality, there is NO business incentive to invest in quality at all. Quality will just remain a nice-to-have, but low on the priority list. Sometimes the company may invest in technical improvements – but they will remain as just wishlists and no actual change will occur.

For 5% of companies, the answer is: Yes.

These companies can NOT compromise on quality. Either the company will ensure high quality standards or the business will close down. There is no choice. Quality is a must-have. This means there is a business imperative for quality.

Unlocking Quality Software in 2024: A Striver Solution

Q: How can companies in the 5% bracket ensure top-notch software quality?

A: Striver offers a direct route! Skip the trial-and-error phase with our tailored Technical Coaching. Transform your real product in months, not years.

🚀 Connect with Striver for Quality Software Products! Launch your MVP and ensure a bug-free product.

✉ Contact us at info@strivertech.com.

Are bugs and slow delivery ok?

The post Are bugs and slow delivery ok? first appeared on Striver Technosoft.

]]>
Unlock Success with React Native: Best Practices by Striver http://www.strivertech.com/unlock-success-with-react-native-best-practices-by-striver/?utm_source=rss&utm_medium=rss&utm_campaign=unlock-success-with-react-native-best-practices-by-striver Wed, 31 Jan 2024 06:54:30 +0000 https://www.strivertech.com/?p=6942 React Native Best Practices Understanding Best Practices in Coding In the coding world, ‘best practices’ refer to guidelines rather than strict rules. While it may seem optional initially, adhering to these suggestions is crucial as your codebase expands. While your code might function adequately without them initially, maintaining its health and readability becomes increasingly challenging […]

The post Unlock Success with React Native: Best Practices by Striver first appeared on Striver Technosoft.

]]>

React Native Best Practices

Understanding Best Practices in Coding

In the coding world, ‘best practices’ refer to guidelines rather than strict rules. While it may seem optional initially, adhering to these suggestions is crucial as your codebase expands. While your code might function adequately without them initially, maintaining its health and readability becomes increasingly challenging as it grows.

 

Alright, let’s get down to the main point. What are the React Native best practices? Well, they’re a bunch of guidelines that you can follow to create a maintainable codebase. In this article, we’ll go into more detail about these practices.

Are you delving into React Native development and striving for excellence in your mobile app projects? Striver brings you valuable insights and best practices to guide you on your journey to success.

Top 6 React Native Best Practices for 2024

Top 6 React Native Best Practices for 2024
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 the order price

function calculatePrice(order) {
return order.price + 200;
}

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 calculatePrice(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 Example

import 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. The state is managed within the component’s constructor, and the render method defines the component’s UI.

Functional Component Example

import 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 invariably.

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:

  1. External imports — react
  2. Internal imports, like relative paths — ../button
  3. In folder imports like ./styles.ts
  4. The imports may be sorted alphabetically in every group
  5. 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.

  1. 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 dependency

yarn 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",
},
},
],
],
}
}
5. Create Responsive Layout in Your React Native App

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.

6. 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.

Dive Deeper with Striver

For an in-depth exploration of these React Native best practices and more, read our featured blog on Medium: React Native Best Practices by Striver.

At Striver, we are committed to empowering developers and businesses with the knowledge and expertise needed to excel in the dynamic world of React Native development. Stay tuned for more insightful content, and let’s shape the future of mobile app development together.

Ready to elevate your React Native projects? Connect with Striver, your trusted partner in innovative software solutions.

 

🚀💻 #ReactNative #MobileAppDevelopment #BestPractices #StriverTech #SoftwareDevelopment #TechInnovation

The post Unlock Success with React Native: Best Practices by Striver first appeared on Striver Technosoft.

]]>
Unlocking Efficiency: Best Practices for GraphQL Queries in React Native http://www.strivertech.com/unlocking-efficiency-best-practices-for-graphql-queries-in-react-native/?utm_source=rss&utm_medium=rss&utm_campaign=unlocking-efficiency-best-practices-for-graphql-queries-in-react-native Thu, 30 Nov 2023 05:43:00 +0000 https://www.strivertech.com/?p=6900 Unlocking Efficiency: Best Practices for GraphQL Queries in React Native Introduction:GraphQL has revolutionized the way we interact with APIs, providing flexibility and efficiency. In this blog, we’ll explore some best practices for crafting GraphQL queries in React Native, enhancing the performance and maintainability of your applications. Understanding GraphQL Queries: GraphQL allows you to request only […]

The post Unlocking Efficiency: Best Practices for GraphQL Queries in React Native first appeared on Striver Technosoft.

]]>

Unlocking Efficiency: Best Practices for GraphQL Queries in React Native

Introduction:
GraphQL has revolutionized the way we interact with APIs, providing flexibility and efficiency. In this blog, we’ll explore some best practices for crafting GraphQL queries in React Native, enhancing the performance and maintainability of your applications.

Understanding GraphQL Queries:
GraphQL allows you to request only the data you need, minimizing the payload size and speeding up data retrieval. Here are some best practices to make the most of your GraphQL queries:

1. Be Specific with Field Selection: Rather than requesting all fields, specify only the ones your component needs. This reduces unnecessary data transfer and improves response times.

Example:

query {
user(id: "123") {
name
email
}
}

2. Utilize Fragments for Reusability: Define fragments for commonly used fields to keep queries DRY (Don’t Repeat Yourself) and enhance code maintainability.

Example:

fragment UserInfo on User {
name
email
}

query {
user(id: "123") {
...UserInfo
}
allUsers {
...UserInfo
}
}

3. Pagination for Large Data Sets: Implement pagination when dealing with large datasets. Use first, last, before, and after arguments to request a specific subset of data.

Example:

query {
posts(first: 10, after: "cursor") {
pageInfo {
hasNextPage
}
edges {
node {
title
}
}
}
}

4. Avoid Deeply Nested Queries: Keep queries flat to prevent over-fetching. Nesting queries too deeply can lead to performance issues.

Example:

query {
user(id: "123") {
posts {
comments {
text
}
}
}
}

5. Use Aliases for Clarity: Aliases help in differentiating between multiple queries of the same type in a single request, enhancing code readability.

Example:

query {
userPosts: user(id: "123") {
posts {
title
}
}
allPosts: posts {
title
}
}
Unlock a wealth of resources with a single request from GraphQL! 🌐

Conclusion:

By following these best practices, you can optimize your GraphQL queries in React Native, resulting in faster data retrieval, improved app performance, and streamlined code. Experiment with these techniques in your projects and witness the efficiency GraphQL can bring to your React Native applications.

The post Unlocking Efficiency: Best Practices for GraphQL Queries in React Native first appeared on Striver Technosoft.

]]>
TypeScript vs. JavaScript: Your Go-to Guide 🚀 http://www.strivertech.com/typescript-vs-javascript-your-go-to-guide/?utm_source=rss&utm_medium=rss&utm_campaign=typescript-vs-javascript-your-go-to-guide Mon, 31 Jul 2023 04:25:20 +0000 https://www.strivertech.com/?p=6866 TypeScript vs. JavaScript: Your Go-to Guide 🚀 Unsure whether to opt for TypeScript or stick with JavaScript for your next project? This comprehensive guide breaks down the distinctions, advantages, and ideal scenarios for using each language. 📚🔍 📝 In the realm of web development, the age-old debate between TypeScript and JavaScript continues to captivate developers. […]

The post TypeScript vs. JavaScript: Your Go-to Guide 🚀 first appeared on Striver Technosoft.

]]>
TypeScript vs. JavaScript: Your Go-to Guide 🚀

Unsure whether to opt for TypeScript or stick with JavaScript for your next project? This comprehensive guide breaks down the distinctions, advantages, and ideal scenarios for using each language. 📚🔍

📝 In the realm of web development, the age-old debate between TypeScript and JavaScript continues to captivate developers. Both languages have their merits and applications, making it essential to grasp their unique attributes. In this blog, we’ll compare TypeScript and JavaScript, shedding light on their respective strengths, use cases and practical scenarios.

TypeScript: The Empowered JavaScript 🔷

💡 TypeScript, a Microsoft creation, is hailed as a superset of JavaScript. With static typing and added features, it elevates the JavaScript experience and enables developers to build more robust applications.

Benefits of TypeScript:

  1. Strong Typing: TypeScript enforces strict typing rules, catching errors during compilation, leading to more reliable codebases.
  2. Enhanced IDE Support: Static types empower modern IDEs to provide better code suggestions and refactoring assistance.
  3. Improved Code Quality: By introducing static types, TypeScript enhances code maintainability and readability.
  4. IDE Integration: TypeScript seamlessly integrates with popular IDEs, offering improved tooling for efficient development.

Ideal Use Cases for TypeScript: 🎯

TypeScript shines in large-scale projects where maintaining code quality and minimizing errors are paramount. It is an excellent choice for enterprise-level applications, complex systems, and collaborative team environments.

JavaScript: The Dynamic Language 📜

💡 JavaScript, the foundation of web development, boasts unparalleled flexibility and simplicity. It powers most websites and web applications, owing to its versatility.

Benefits of JavaScript:

  1. Lightweight: JavaScript’s lightweight nature ensures faster loading times, making it ideal for front-end development.
  2. Ubiquitous: Supported across all modern browsers, JavaScript enjoys widespread compatibility, reaching a broad audience.
  3. Flexibility: Its dynamic characteristics allow developers to create and modify objects and functions with ease.

Ideal Use Cases for JavaScript: 🎯

JavaScript is the go-to choice for small to medium-sized projects, quick prototypes, and applications requiring rapid development and deployment. It excels in front-end web development, offering agility and interactivity.

Unraveling TypeScript vs. JavaScript: Your Definitive Guide with STriver Insights

TypeScript or JavaScript? Developers contemplate this choice for greenfield web or Node.js projects, but it’s a question worth considering for existing projects too. A superset of JavaScript, TypeScript offers all of the features of JavaScript plus some additional perks. TypeScript intrinsically encourages us to code cleanly, making the code more scalable. However, projects can contain as much plain JavaScript as we like, so using TypeScript is not an all-or-nothing proposition.

The Relationship Between TypeScript and JavaScript

TypeScript adds an explicit type system to JavaScript, allowing for the strict enforcement of variable types. TypeScript runs its type checks while transpiling—a form of compiling that converts TypeScript code to the JavaScript code web browsers and Node.js understand.

TypeScript vs. JavaScript Examples

Let’s start with a valid JavaScript snippet:

let var1 = "Hello";
var1 = 10;
console.log(var1); 

Here, var1 starts out as a string, then becomes a number.

Since JavaScript is only loosely typed, we can redefine var1 as a variable of any type—from a string to a function—at any time.

Executing this code outputs 10.

Now, let’s change this code into TypeScript:

let var1: string = "Hello";
var1 = 10;
console.log(var1);

In this case, we declare var1 to be a string. We then try to assign a number to it, which isn’t allowed by TypeScript’s strict type system. Transpiling results in an error:

TSError: ⨯ Unable to compile TypeScript:
src/snippet1.ts:2:1 - error TS2322: Type 'number' is not assignable to type 'string'.

2 var1 = 10;

If we were to instruct the transpiler to treat the original JavaScript snippet as if it were TypeScript, the transpiler would automatically infer that var1 should be a string | number. This is a TypeScript union type, which allows us to assign var1 a string or a number at any time. Having resolved the type conflict, our TypeScript code would transpile successfully. Executing it would produce the same result as the JavaScript example.

Choosing the Right Language: 🤔

Selecting TypeScript or JavaScript hinges on project-specific requirements, team expertise, and long-term goals. Consider the following factors:

  • Project Scale: TypeScript’s static typing significantly enhances code quality for extensive and complex applications.
  • Team Familiarity: Sticking with JavaScript might be the optimal choice if your team is already well-versed and requires rapid development.
  • Learning Curve: TypeScript may have a steeper learning curve for developers accustomed to JavaScript. Assess your team’s adaptability to a typed language.

Conclusion: 💡

TypeScript and JavaScript are both powerful tools, each with its unique strengths and best-suited use cases. While TypeScript excels in large-scale projects demanding enhanced code quality, JavaScript remains the go-to for smaller applications requiring rapid development. By understanding their distinctions, developers can make informed choices, optimize efficiency and deliver exceptional web experiences.

Remember, there’s no one-size-fits-all answer. Evaluate your project’s specific needs, consider your team’s expertise, and make a well-informed decision to propel your web or app development journey forward.

The post TypeScript vs. JavaScript: Your Go-to Guide 🚀 first appeared on Striver Technosoft.

]]>
How to Build a React Native QR Scanner: An RNCamera Tutorial http://www.strivertech.com/how-to-build-a-react-native-qr-scanner-an-rncamera-tutorial/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-build-a-react-native-qr-scanner-an-rncamera-tutorial Tue, 11 Jul 2023 07:24:56 +0000 https://www.strivertech.com/?p=6853 How to Build a React Native QR Scanner: An RNCamera Tutorial Capture picture-perfect moments with ease using the camera functionality in React Native. In this comprehensive tutorial, we’ll walk you through the process of integrating camera features into your app, from capturing photos and videos to applying filters and accessing device-specific functionalities. Let’s dive in […]

The post How to Build a React Native QR Scanner: An RNCamera Tutorial first appeared on Striver Technosoft.

]]>
How to Build a React Native QR Scanner: An RNCamera Tutorial

Capture picture-perfect moments with ease using the camera functionality in React Native. In this comprehensive tutorial, we’ll walk you through the process of integrating camera features into your app, from capturing photos and videos to applying filters and accessing device-specific functionalities. Let’s dive in and unleash the power of React Native camera!

In this React Native QR code scanner tutorial, the app we create will be able to read QR codes in real-time and render their content to the screen at the time of detection. We will be using React Native’s CLI Quickstart.

(Note: If you need help setting this up, you can always refer to the React Native Getting Started page—don’t forget to click on the “React Native CLI Quickstart” button, as “Expo CLI Quickstart” comes preselected at the time of writing this article.)

Why a React Native Scanner?

React Native is a valuable framework that borrows React’s paradigm and design principles to enable lightning fast, cross-platform development of snappy UIs. Facebook, Airbnb, Uber, and many others already have their latest apps built with React Native.

What Is React Native Camera?

React Native Camera (RNCamera) is the go-to component when it comes to implementing camera functionality in a React Native app. This component helps you communicate with the native OS through some simple functions so you can use device hardware. You can build your apps around these functions without getting into the hassle of native code. RNCamera already supports:

  • Photographs
  • Videos
  • Face detection
  • Barcode scanning
  • Text recognition (Android only)

Note that RNCamera used to come in two flavors:

  1. RNCamera
  2. RCTCamera (deprecated)

…so make sure to use RNCamera so that you can keep getting the latest updates.

Note: React Native Camera is heavily based on the Expo camera module and going back and forth between the two is pretty easy.

Creating Your First App Using RNCamera

Before we begin our React Native QR scanner, there are some dependencies we’ll need to install.

Installing RNCamera’s Dependencies

Our setup needs a minimum of JDK version 1.7 (which you most likely have) and if you’re on Android you’ll require buildToolsVersion newer than 25.0.2. (To be sure, there is a more detailed and up-to-date list in the docs.)

First let’s get started by creating a new React Native project:

react-native init CameraExample

Now let’s deploy the first version of our React Native QR scanner example over our phone.

cd CameraExample
react-native run-android

Now it’s time to install the react-native-camera package in our project. We will use the “Mostly automatic install with react-native” option. (There are others like Mostly automatic install with CocoaPods and Manual install, but we will stick to the first option, as it’s the most efficient.) Simply run:

npm install react-native-camera --save
react-native link react-native-camera

You must also add the following permissions to android/app/src/main/AndroidManifest.xml:

   package="com.cameraexample">

     <uses-permission android:name="android.permission.INTERNET" />
+    <uses-permission android:name="android.permission.CAMERA" />
+    <uses-permission android:name="android.permission.RECORD_AUDIO"/>
+    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

     <application
       android:name=".MainApplication"

You’ll also need to set the dimension strategy in android/app/build.gradle—it has no default and you’ll get an error if you don’t define it:

     defaultConfig {
         applicationId "com.cameraexample"
         minSdkVersion rootProject.ext.minSdkVersion
+        missingDimensionStrategy 'react-native-camera', 'general'
         targetSdkVersion rootProject.ext.targetSdkVersion
         versionCode 1
         versionName "1.0"

Note: The dimension strategy should normally be set to general as above. However, you can set it to mlkit instead, if you’d like to use MLKit for text/face/barcode recognition.

After the installation, you will need to use run-android to install the new dependencies:

react-native run-android

If everything went well, you should see the same React Native welcome screen on your device or simulator again.

Setting Up the Camera

First, let’s start by modifying App.js and importing RNCamera there:

import { RNCamera } from 'react-native-camera';

Next, we’ll modify the render function to include our newly imported RNCamera. Notice the style attribute added to the camera in order for it to take the full screen. Without these styles, you may not be able to see the camera render on your screen, as it will not occupy any space:

   render() {
     return (
       <View style={styles.container}>
-        <Text style={styles.welcome}>Welcome to React Native!</Text>
-        <Text style={styles.instructions}>To get started, edit App.js</Text>
-        <Text style={styles.instructions}>{instructions}</Text>
+        <RNCamera
+          ref={ref => {
+            this.camera = ref;
+          }}
+          style={{
+            flex: 1,
+            width: '100%',
+          }}
+        >
+        </RNCamera>
       </View>
     );
   }

After adding this code, your interface should have the camera on, full-screen, just like the screenshot below:

Now our React Native barcode scanner can see barcodes (as we can see our test QR codes showing on the monitor above) but can’t read them yet. Let’s use RNCamera’s algorithm to recognize what is written inside each of them.

Reading Barcode Information

In order to read barcode information, we will use the onGoogleVisionBarcodesDetected prop so that we can call a function and extract the information. Let’s add that in the <RNCamera> component and link it to a barcodeRecognized function to take care of it. Note that onGoogleVisionBarcodesDetected returns an object containing the barcodes property, which contains an array of all the barcodes recognized in the camera.

Note: The onGoogleVisionBarcodesDetected QR code technology is only available on Android, but if you’d like a cross-platform approach, you’d better go with onBarCodeRead. It supports only a single barcode at a time—using it as a fallback is left as an exercise for the reader.

Here’s how our <RNCamera> should look after adding onGoogleVisionBarcodesDetected:

       <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={{
            flex: 1,
            width: '100%',
          }}
          onGoogleVisionBarcodesDetected={this.barcodeRecognized}
        >
        </RNCamera>

And now we can handle the barcodes in App.js with the function below, which will only warn us when a barcode is detected and should display its content on the screen:

  barcodeRecognized = ({ barcodes }) => {
    barcodes.forEach(barcode => console.warn(barcode.data))
  };
Rendering Barcode Overlays

The previous screenshot now shows the information contained in the barcode but does not allow us to know which message belongs to which barcode. For this, we will go deeper into the barcodes returned from onGoogleVisionBarcodesDetected and try to pinpoint each of the barcodes on our screen.

But first, we will need to save the recognized barcodes into the state so that we can access it and render an overlay based on the contained data. We will now modify our previously defined function to look like this:

barcodeRecognized = ({ barcodes }) => this.setState({ barcodes });

We will now need to add a state object initialized to an empty array of barcodes so that it doesn’t create any errors in our render functions:

export default class App extends Component<Props> {
  state = {
    barcodes: [],
  }
// ...

Let’s now create the renderBarCodes function which should be added inside the <RNCamera> component:

        <RNCamera
          ref={ref => {
            this.camera = ref;
          }}
          style={{
            flex: 1,
            width: '100%',
          }}
          onGoogleVisionBarcodesDetected={this.barcodeRecognized}
        >
          {this.renderBarcodes()}
        </RNCamera>

This function should now take the barcodes recognized from the state and show them on-screen:

  renderBarcodes = () => (
    <View>
      {this.state.barcodes.map(this.renderBarcode)}
    </View>
  );

Notice that the mapping is pointed to renderBarcode which should render each barcode on the screen. I’ve added some minor styling in order for us to be able to recognize those easily:

 renderBarcode = ({ bounds, data }) => (
    <React.Fragment key={data + bounds.origin.x}>
      <View
        style={{
          borderWidth: 2,
          borderRadius: 10,
          position: 'absolute',
          borderColor: '#F00',
          justifyContent: 'center',
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          padding: 10,
          ...bounds.size,
          left: bounds.origin.x,
          top: bounds.origin.y,
        }}
      >
        <Text style={{
          color: '#F00',
          flex: 1,
          position: 'absolute',
          textAlign: 'center',
          backgroundColor: 'transparent',
        }}>{data}</Text>
      </View>
    </React.Fragment>
  );

Each barcode recognized has:

  • bounds property to tell us where on our screen the barcode was found, which we’ll use to render the overlay for it
  • data property that shows us what is encoded in that specific barcode
  • type property which tells us what kind of barcode it is (2D, QR, etc.)

Using those three parameters as we have in the render function above gives the following result:

 

By following this comprehensive tutorial, you’ll be equipped with the knowledge and skills to integrate camera functionality into your React Native app seamlessly. Remember to experiment with different features and customize the implementation according to your app’s requirements. Get ready to wow your users with stunning images and videos captured within your app!

The post How to Build a React Native QR Scanner: An RNCamera Tutorial first appeared on Striver Technosoft.

]]>
Transcribing Audio to Text in React Native: Unlocking New Possibilities http://www.strivertech.com/transcribing-audio-to-text-in-react-native-unlocking-new-possibilities/?utm_source=rss&utm_medium=rss&utm_campaign=transcribing-audio-to-text-in-react-native-unlocking-new-possibilities Fri, 07 Jul 2023 04:45:42 +0000 https://www.strivertech.com/?p=6838 Harness the Power of React Native to Convert Audio into Text with Ease Transcribing Audio to Text in React Native: Unlocking New Possibilities In today’s digital era, the ability to convert audio into text has become increasingly valuable for developers. Whether it’s for voice commands, transcription services, or enhancing accessibility, incorporating audio-to-text functionality can greatly […]

The post Transcribing Audio to Text in React Native: Unlocking New Possibilities first appeared on Striver Technosoft.

]]>

Harness the Power of React Native to Convert Audio into Text with Ease

Transcribing Audio to Text in React Native: Unlocking New Possibilities

In today’s digital era, the ability to convert audio into text has become increasingly valuable for developers. Whether it’s for voice commands, transcription services, or enhancing accessibility, incorporating audio-to-text functionality can greatly enrich the user experience of your React Native apps. In this blog, we will explore the process of transcribing audio to text using React Native and delve into real-life examples that demonstrate its potential.

Section 1: Understanding Audio-to-Text Conversion

  • Exploring the importance of audio-to-text conversion in modern apps
  • Briefly discussing the underlying technologies and techniques involved
  • Highlighting the benefits and use cases of integrating audio-to-text functionality

Section 2: Getting Started with React Native Audio-to-Text

  • Discussing the prerequisites and setup requirements for implementing audio-to-text conversion in React Native
  • Providing step-by-step instructions for installing the necessary libraries and dependencies
  • Outlining the key components and APIs involved in the process

Section 3: Transcribing Audio to Text: A Practical Example

  • Walking through a hands-on example that demonstrates how to transcribe audio to text using React Native
  • Showcasing the integration of popular libraries and APIs for audio processing and transcription
  • Providing code snippets and explanations to guide developers through the implementation process

Section 4: Enhancing Your App’s Functionality

  • Exploring additional features and enhancements that can be implemented alongside audio-to-text conversion
  • Discussing options for storing and managing transcriptions within the app
  • Offering tips and best practices for optimizing performance and accuracy

Developer Story: Insights from Experienced Developers

  • Interviewing experienced developers who have implemented audio-to-text conversion in their React Native projects
  • Sharing their experiences, challenges, and tips for successfully incorporating this feature
  • Inspiring other developers with real-life examples of how audio-to-text conversion has enhanced their apps

In this blog, we have explored the fascinating world of transcribing audio to text in React Native. By harnessing the power of this feature, developers can create more versatile and accessible apps that cater to a broader audience. With the step-by-step guide, practical examples, and insights from experienced developers, you now have the knowledge and tools to embark on your own audio-to-text conversion journey. So, let your creativity soar and unlock new possibilities with React Native’s audio-to-text capabilities.

Remember to stay tuned for future blog posts and updates as we continue to dive deeper into the world of React Native development.

Hashtags: #ReactNative #AudioToText #Transcription #Development #MobileApps

The post Transcribing Audio to Text in React Native: Unlocking New Possibilities first appeared on Striver Technosoft.

]]>
How to Integrate WalletConnect with React Native http://www.strivertech.com/how-to-integrate-walletconnect-with-react-native/?utm_source=rss&utm_medium=rss&utm_campaign=how-to-integrate-walletconnect-with-react-native Fri, 30 Jun 2023 04:56:52 +0000 https://www.strivertech.com/?p=6807 How to Integrate WalletConnect with React Native A step-by-step guide to connecting your React Native apps to Ethereum wallets with WalletConnect WalletConnect is a cross-platform protocol that allows users to connect their Ethereum wallets to dapps on mobile and desktop devices. It’s a secure and easy way to sign transactions and interact with decentralized applications. […]

The post How to Integrate WalletConnect with React Native first appeared on Striver Technosoft.

]]>

How to Integrate WalletConnect with React Native

A step-by-step guide to connecting your React Native apps to Ethereum wallets with WalletConnect

WalletConnect is a cross-platform protocol that allows users to connect their Ethereum wallets to dapps on mobile and desktop devices. It’s a secure and easy way to sign transactions and interact with decentralized applications.

In this blog post, we’ll show you how to integrate WalletConnect with your React Native dapp. We’ll cover the following topics:

What is WalletConnect?

WalletConnect is a protocol that allows users to connect their Ethereum wallets to apps on mobile and desktop devices. It’s a secure and easy way to sign transactions and interact with decentralized applications.

WalletConnect works by generating a QR code that is scanned by the user’s wallet app. The wallet app then authenticates the user and establishes a secure connection with the app.

How to install the WalletConnect React Native library

The first step is to install the WalletConnect React Native library. You can do this by running the following command:

npm install @walletconnect/react-native-dapp

How to create a WalletConnect connection

Once you have installed the library, you can create a WalletConnect connection by calling the WalletConnectProvider component. This component takes a few props, including the following:

  • clientMeta: This is an object that contains information about your app, such as the name and description.
  • onConnect: This is a function that is called when the user connects their wallet to your app.
  • onDisconnect: This is a function that is called when the user disconnects their wallet from your app.

Example

Here is an example of how to use WalletConnect in a React Native app:

import React, { useState } from "react";
import WalletConnectProvider from "@walletconnect/react-native-dapp";

function App() {
const [connected, setConnected] = useState(false);

return (
<WalletConnectProvider
clientMeta={{
name: "My Dapp",
description: "A simple example of how to use WalletConnect with React Native",
}}
onConnect={() => setConnected(true)}
onDisconnect={() => setConnected(false)}
>
{connected ? (
<h1>You are connected!</h1>
) : (
<h1>You are not connected.</h1>
)}
</WalletConnectProvider>
);
}

export default App;

This code will create a WalletConnect connection and display a message depending on whether the user is connected or not.

How to sign transactions with WalletConnect

Once you have created a WalletConnect connection, you can use it to sign transactions. To do this, you can call the signTransaction method on the WalletConnectProvider component. This method takes a transaction object as a prop, and it returns the signed transaction.

Wallet connect supported by over 300 wallets.

The post How to Integrate WalletConnect with React Native first appeared on Striver Technosoft.

]]>
Enhancing Your React Native App with Powerful Functionality http://www.strivertech.com/enhancing-your-react-native-app-with-powerful-functionality/?utm_source=rss&utm_medium=rss&utm_campaign=enhancing-your-react-native-app-with-powerful-functionality Wed, 28 Jun 2023 07:34:36 +0000 https://www.strivertech.com/?p=6762 Enhancing Your React Native App with Powerful Functionality​ Discover the Most Useful React Native Libraries for Maps, Camera, Image, and Navigation In the ever-evolving world of mobile app development, React Native has gained significant popularity for its ability to create cross-platform apps with a single codebase. To enhance the functionality and user experience of React […]

The post Enhancing Your React Native App with Powerful Functionality first appeared on Striver Technosoft.

]]>

Discover the Most Useful React Native Libraries for Maps, Camera, Image, and Navigation

In the ever-evolving world of mobile app development, React Native has gained significant popularity for its ability to create cross-platform apps with a single codebase. To enhance the functionality and user experience of React Native apps, developers can leverage various libraries and APIs. In this blog post, we will explore some of the most essential and widely used libraries for integrating Maps, Cameras, Image handling, and Navigation features into React Native apps.

Unleash the Power of React Native with Powerful Functionalities 🚀
Maps:
Navigating the World Within Your App 🗺

Maps are a crucial component of many mobile applications, enabling location-based services and route tracking. With the “react-native-maps” library, integrating Maps into your React Native app becomes a breeze. Take a look at this code snippet for a quick integration example:

import MapView, { Marker } from 'react-native-maps';

const App = () => {
return (
<MapView
style={{ flex: 1 }}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
>
<Marker
coordinate={{
latitude: 37.78825,
longitude: -122.4324,
}}
title="Marker Title"
description="Marker Description"
/>
</MapView>
);
};

export default App;
Camera:
Capturing Moments with Ease 📸

Integrating camera functionality adds a personal touch to your app and allows users to capture memorable moments effortlessly. The “react-native-camera” library provides powerful camera features, including device camera access, image capture, and video recording. Check out this simple code snippet to get started:

import { RNCamera } from 'react-native-camera';

const App = () => {
const handleCapture = async () => {
if (cameraRef) {
const options = { quality: 0.5, base64: true };
const data = await cameraRef.takePictureAsync(options);
console.log(data.uri);
}
};

return (
<RNCamera
ref={(ref) => (cameraRef = ref)}
style={{ flex: 1 }}
type={RNCamera.Constants.Type.back}
>
<TouchableOpacity onPress={handleCapture}>
<Text style={{ fontSize: 16, color: 'white' }}>Take Photo</Text>
</TouchableOpacity>
</RNCamera>
);
};

export default App;
Image:
Handling Visual Content with Efficiency 🌄

Efficiently managing images, such as loading, caching, and resizing, is vital for delivering a seamless user experience. The “react-native-fast-image” library offers optimized image loading capabilities, supporting placeholder images, error handling, and image prefetching. Here’s a snippet to get you started:

import FastImage from 'react-native-fast-image';

const App = () => {
return (
<FastImage
style={{ width: 200, height: 300 }}
source={{
uri: 'https://example.com/image.jpg',
priority: FastImage.priority.normal,
}}
resizeMode={FastImage.resizeMode.cover}
/>
);
};

export default App;
Navigation:
Seamlessly Moving Between Screens 🔄

Efficient navigation is crucial for creating intuitive app experiences with smooth transitions between screens. React Navigation is a popular library that offers a wide range of navigators, including stack, tab, and drawer navigators. Here’s a basic example using stack navigation:

import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

const HomeScreen = () => {
return <Text>Welcome to the Home Screen!</Text>;
};

const DetailsScreen = () => {
return <Text>These are the Details!</Text>;
};

const AppNavigator = createStackNavigator(
{
Home: HomeScreen,
Details: DetailsScreen,
},
{
initialRouteName: 'Home',
}
);

export default createAppContainer(AppNavigator);

By incorporating these essential React Native libraries for Maps, Camera, Image handling, and Navigation, developers can enrich their app functionalities and provide a seamless user experience. Leveraging these libraries empowers developers to build robust cross-platform apps while enjoying the flexibility and power of React Native.

Remember, while libraries and SDKs offer tremendous convenience, it’s essential to thoroughly understand their documentation and explore native code options when necessary. With React Native, developers have the freedom to access every device API and write native code to achieve limitless possibilities.

Stay tuned for more exciting React Native tips and tricks, and happy coding! 🚀

 #ReactNative #MobileAppDevelopment #Maps #Camera #ImageHandling #Navigation #JavaScript #CrossPlatform #AppDevelopment

Follow us on Social! 🌐📱

Enhancing Your React Native App with Powerful Functionality​

Unleash the Power of React Native with Powerful Functionalities 🚀

The post Enhancing Your React Native App with Powerful Functionality first appeared on Striver Technosoft.

]]>