<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Niraj Dhungana</title>
    <description>The latest articles on DEV Community by Niraj Dhungana (@fsniraj).</description>
    <link>https://dev.to/fsniraj</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F635667%2Fad844acf-e07a-4fc0-9267-ad0231757d91.png</url>
      <title>DEV Community: Niraj Dhungana</title>
      <link>https://dev.to/fsniraj</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/fsniraj"/>
    <language>en</language>
    <item>
      <title>Live Search in React js - Select with Mouse or Keyboard</title>
      <dc:creator>Niraj Dhungana</dc:creator>
      <pubDate>Sun, 11 Sep 2022 16:55:36 +0000</pubDate>
      <link>https://dev.to/fsniraj/live-search-in-react-js-select-with-mouse-or-keyboard-54nf</link>
      <guid>https://dev.to/fsniraj/live-search-in-react-js-select-with-mouse-or-keyboard-54nf</guid>
      <description>&lt;p&gt;Displaying the live search results to the user while they are typing in the search bar is a great user experience. But creating the live search field with all the features. Like, select with a mouse, move selections on key up down and hide the search bar on blur.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsm1rurh45iyqgg10f32v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsm1rurh45iyqgg10f32v.gif" alt="Final Live Search Result"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a little bit of a challenging task. So, let's try to go through all the challenges and create this awesome live search field. Where users can select the result with a mouse or by using the keyboard also the results will be hidden if we click outside.&lt;/p&gt;

&lt;p&gt;The things we will cover&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#React%20&amp;amp;%20Tailwind%20Project%20Setup" rel="noopener noreferrer"&gt;React &amp;amp; Tailwind Project Setup&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Creating%20a%20Search%20Bar" rel="noopener noreferrer"&gt;Creating a Search Bar&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Container%20to%20Render%20Search%20Results" rel="noopener noreferrer"&gt;Container to Render Search Results&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Creating%20a%20Fully%20Customizable%20Component" rel="noopener noreferrer"&gt;Creating a Fully Customizable Component&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Conditionally%20Rendering%20Results" rel="noopener noreferrer"&gt;Conditionally Rendering Results&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Adding%20a%20Live%20Search%20Logic" rel="noopener noreferrer"&gt;Adding a Live Search Logic&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Selecting%20Results%20on%20Key%20up-down" rel="noopener noreferrer"&gt;Selecting Results on Key up-down&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Styling%20the%20Focused%20Item" rel="noopener noreferrer"&gt;Styling the Focused Item&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Selecting%20the%20Results" rel="noopener noreferrer"&gt;Selecting the Results&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Hiding%20Results%20onBlur" rel="noopener noreferrer"&gt;Hiding Results onBlur&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.fsniraj.dev/blogs/live-search-in-react-js-select-with-mouse-or-keyboard#Updating%20the%20value%20inside%20the%20search%20bar" rel="noopener noreferrer"&gt;Updating the value inside the search bar&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  React &amp;amp; Tailwind Project Setup
&lt;/h2&gt;

&lt;p&gt;To create this demo we are going to use obviously the React JS and Tailwind CSS for styling. If you want to you can use any other CSS framework or library. This logic will work for all of them.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;If you don't know Tailwind CSS is a framework with a bunch of utility class names to style our HTML.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you already have a project, you can directly add this logic to your existing project as well. But if you are starting from the ground like me run these commands to initialize a new project.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app live-search --template typescript
# or
npx create-react-app live-search // if you are using JavaScript
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Once you run one of the commands, the project will be initialized. Now you can install Tailwind CSS. First, change the directory with &lt;code&gt;cd live-search&lt;/code&gt; and run these commands.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then you have to go to your &lt;code&gt;tailwind.config.js&lt;/code&gt; file and add these things inside your content.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// tailwind.config.js
module.exports = {
  content: ["./src/**/*.{js,jsx,ts,tsx}",],
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then go to your &lt;code&gt;index.css&lt;/code&gt; and replace all of the code with these three lines of code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// index.css
// remove old CSS and add them
@tailwind base;
@tailwind components;
@tailwind utilities;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating a Search Bar
&lt;/h2&gt;

&lt;p&gt;A search bar is just an &lt;code&gt;input&lt;/code&gt; element. But we will add a little bit of style to it so that it looks a little bit nice. For that, let's create a file called &lt;code&gt;SearchBar.tsx&lt;/code&gt; (or jsx) inside the src folder and add these codes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside SearchBar.tsx
import React, { FC } from "react";

interface Props&amp;lt;T&amp;gt; {
  value?: string;
  notFound?: boolean;
  onChange?: React.ChangeEventHandler;
  results?: T[];
  renderItem: (item: T) =&amp;gt; JSX.Element;
  onSelect?: (item: T) =&amp;gt; void;
}

const SearchBar = &amp;lt;T extends object&amp;gt;({ }: Props&amp;lt;T&amp;gt;): JSX.Element =&amp;gt; {
  return (
    {/* Search bar */}
    &amp;lt;input
      type="text"
      className="w-full p-2 text-lg rounded border-2 border-gray-500 outline-none"
      placeholder="Search here..."
    /&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I don't think I have to explain these class names. They are explaining themselves. But these &lt;code&gt;interface Props&lt;/code&gt; might look a little scary. This is just a Typescript thing which I will explain when we need them. So, let's render this component inside our &lt;code&gt;App.tsx&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside App.tsx
const App = () =&amp;gt; {
  return (
    &amp;lt;div className="max-w-3xl mx-auto mt-10"&amp;gt;
      &amp;lt;SearchBar /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here I am using the fixed width for the &lt;code&gt;div&lt;/code&gt; so that I can use this &lt;code&gt;mx-auto&lt;/code&gt; to bring this &lt;code&gt;div&lt;/code&gt; to the center of the webpage. If you try to run this code it will throw an error. Because &lt;code&gt;renderItem&lt;/code&gt; is the required prop. Comment it out if you want to see the change.&lt;/p&gt;

&lt;h2&gt;
  
  
  Container to Render Search Results
&lt;/h2&gt;

&lt;p&gt;Now we need a container to render our results. So for that, we will wrap our search input inside a &lt;code&gt;div&lt;/code&gt; with class &lt;code&gt;relative&lt;/code&gt;. And we will render a &lt;code&gt;div&lt;/code&gt; below the input element with class absolute. With these classes, we will render the search container right below the input field.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx

const SearchBar = &amp;lt;T extends object&amp;gt;({ }: Props&amp;lt;T&amp;gt;): JSX.Element =&amp;gt; {
  return (
    &amp;lt;div className="relative"&amp;gt;
      &amp;lt;input ...  /&amp;gt;
     {/* Results Wrapper */}
      &amp;lt;div className="absolute mt-1 w-full p-2 bg-white shadow-lg rounded-bl rounded-br max-h-36 overflow-y-auto"&amp;gt;&amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With the help of other classes, like &lt;code&gt;max-h-36 overflow-y-auto&lt;/code&gt;. It will create a container with a fixed height and show the scroll bar if the results are longer.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a Fully Customizable Component
&lt;/h2&gt;

&lt;p&gt;Now let's use the first props from inside the interface.  As you see here we are using a little weird syntax for the &lt;code&gt;interface&lt;/code&gt; and &lt;code&gt;SearchBar&lt;/code&gt; components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Props&amp;lt;T&amp;gt; { 
  results?: T[];
  renderItem: (item: T) =&amp;gt; JSX.Element;
  onSelect?: (item: T) =&amp;gt; void;
}

const SearchBar = &amp;lt;T extends object&amp;gt;({}:Props&amp;lt;T&amp;gt;) ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is because we want to make this search bar so customizable. So that, it can take, render and give the same data type back to our &lt;code&gt;renderItem&lt;/code&gt; and &lt;code&gt;onSelect&lt;/code&gt; methods. Now you don't need to worry about types anymore. Typescript will grab the type from &lt;code&gt;results&lt;/code&gt; and distribute it to &lt;code&gt;renderItem&lt;/code&gt; and &lt;code&gt;onSelect&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now finally see how we can render our results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside SearchBar.tsx
const SearchBar = &amp;lt;T extends object&amp;gt;({ results = [], renderItem }: Props&amp;lt;T&amp;gt;): JSX.Element =&amp;gt; {
  return (
    &amp;lt;div className="relative"&amp;gt;
      {/* Search bar */}
      &amp;lt;input ... /&amp;gt;
      {/* Results Wrapper */}
      &amp;lt;div className="..."&amp;gt;
        {/* Results Lists Goes here */}
        &amp;lt;div className="space-y-2"&amp;gt;
          {results.map((item, index) =&amp;gt; {
            return (
              &amp;lt;div
                key={index}
                className="cursor-pointer hover:bg-black hover:bg-opacity-10 p-2"
              &amp;gt;
                {renderItem(item)}
              &amp;lt;/div&amp;gt;
            );
          })}
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Very first thing, don't forget to give your &lt;code&gt;results&lt;/code&gt; prop a default value empty array &lt;code&gt;[]&lt;/code&gt;. It will prevent unwanted errors. Then we are using &lt;code&gt;resutls.map&lt;/code&gt; to render our results. Where we have &lt;code&gt;renderItem&lt;/code&gt; method to render results. We have to pass this method from &lt;code&gt;App.tsx&lt;/code&gt; which we will see later. &lt;/p&gt;

&lt;p&gt;Then we have a wrapper div for &lt;code&gt;renderItem&lt;/code&gt; with classes, &lt;code&gt;hover:bg-black hover:bg-opacity-10&lt;/code&gt;. It is very important to give the user feedback on results hover. These classes will add &lt;code&gt;background-color&lt;/code&gt; of black with &lt;code&gt;opacity: 0.1&lt;/code&gt; on the result hover.&lt;/p&gt;

&lt;p&gt;Ok, now let's try to pass some data to our &lt;code&gt;SearchBar&lt;/code&gt;. Because we used that &lt;code&gt;&amp;lt;T&amp;gt;&lt;/code&gt; generic type we can pass any type of data but inside an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const profiles = [
  { id: "1", name: "Allie Grater" },
  { id: "2", name: "Aida Bugg" },
  { id: "3", name: "Gabrielle" },
  { id: "4", name: "Grace" },
  { id: "5", name: "Hannah" },
  { id: "6", name: "Heather" },
  { id: "7", name: "John Doe" },
  { id: "8", name: "Anne Teak" },
  { id: "9", name: "Audie Yose" },
  { id: "10", name: "Addie Minstra" },
  { id: "11", name: "Anne Ortha" },
];
const App = () =&amp;gt; {
  return (
    &amp;lt;div className="max-w-3xl mx-auto mt-10"&amp;gt;
      &amp;lt;SearchBar results={profiles} renderItem={(item) =&amp;gt; &amp;lt;p&amp;gt;{item.name}&amp;lt;/p&amp;gt;} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As I told you earlier you don't need to worry about the types for &lt;code&gt;renderItem&lt;/code&gt; and &lt;code&gt;onSelect&lt;/code&gt;. Here is the result if you hover over an item you will see its type. Cool right?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjuxhshtuya01trnl0xp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fxjuxhshtuya01trnl0xp.png" alt="typescript in action"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now if you save your file and run the project with &lt;code&gt;npm start&lt;/code&gt;. You will see something like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdyzgc1na0l1ldi95x0lu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdyzgc1na0l1ldi95x0lu.png" alt="search results"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conditionally Rendering Results
&lt;/h2&gt;

&lt;p&gt;Currently, these results are always visible so, let's solve this issue. For that, we can simply add a state called &lt;code&gt;showResults&lt;/code&gt; and display the results according to the value of this state.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside SearchBar.tsx
const SearchBar = ... {
  const [showResults, setShowResults] = useState(true);

  // To toggle the search results as result changes
  useEffect(() =&amp;gt; {
    if (results.length &amp;gt; 0 &amp;amp;&amp;amp; !showResults) setShowResults(true);

    if (results.length &amp;lt;= 0) setShowResults(false);
  }, [results]);

   return ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The logic is pretty straightforward if there are results and the &lt;code&gt;showResults&lt;/code&gt; state is &lt;code&gt;false&lt;/code&gt; only then make it &lt;code&gt;true&lt;/code&gt;. Otherwise, make it false. These logics will now hide and show our search results as the result changes its length.&lt;/p&gt;

&lt;p&gt;But for that, we have to add the condition if &lt;code&gt;showResults&lt;/code&gt; is &lt;code&gt;true&lt;/code&gt; only then render the results.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const SearchBar = ... {
 ...
  return (
    &amp;lt;div className="relative"&amp;gt;
      {/* Search bar */}
      &amp;lt;input ... /&amp;gt;
      {/* Results Wrapper */}
      {showResults ? &amp;lt;div className="..."&amp;gt;
        {/* Results Lists Goes here */}
        &amp;lt;div className="space-y-2"&amp;gt;...&amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt; : null}
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Adding a Live Search Logic
&lt;/h2&gt;

&lt;p&gt;Now let's write a little piece of code to add a fake search logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
const SearchBar = &amp;lt;T extends object&amp;gt;({onChange, ... }: Props&amp;lt;T&amp;gt;): JSX.Element =&amp;gt; {
return (...
  &amp;lt;input
     onChange={onChange}
   /&amp;gt;
...

// App.tsx

const profiles = [...]
const App = () =&amp;gt; {
  const [results, setResults] = useState&amp;lt;{ id: string; name: string }[]&amp;gt;();

type changeHandler = React.ChangeEventHandler&amp;lt;HTMLInputElement&amp;gt;;
  const handleChange: changeHandler = (e) =&amp;gt; {
    const { target } = e;
    if (!target.value.trim()) return setResults([]);

    const filteredValue = profiles.filter((profile) =&amp;gt;
      profile.name.toLowerCase().startsWith(target.value)
    );
    setResults(filteredValue);
  };

  return (
    &amp;lt;div className="max-w-3xl mx-auto mt-10"&amp;gt;
      &amp;lt;SearchBar
        onChange={handleChange}
        results={results}
        renderItem={(item) =&amp;gt; &amp;lt;p&amp;gt;{item.name}&amp;lt;/p&amp;gt;}
      /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Even though this is too much code the logic is simple. First, we destructure the &lt;code&gt;onChange&lt;/code&gt; inside &lt;code&gt;SearchBar&lt;/code&gt; component and assigned it to the input element.&lt;/p&gt;

&lt;p&gt;Then inside &lt;code&gt;App.tsx&lt;/code&gt; we are handling the change event for &lt;code&gt;SearchBar&lt;/code&gt;. So for the &lt;code&gt;handleChange&lt;/code&gt; we are just using the &lt;code&gt;array filter&lt;/code&gt; method to filter out the matching results. &lt;/p&gt;

&lt;p&gt;If we found the results we will add them to the new state called results and if we have an empty input field we will reset those results to an empty array.&lt;/p&gt;

&lt;p&gt;And at the end instead of the &lt;code&gt;profiles&lt;/code&gt;, we will pass the &lt;code&gt;results&lt;/code&gt; state to the &lt;code&gt;results&lt;/code&gt; prop. If you do this you should see the search results only if you type out the correct profile names.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgljrmqkqd0jz8qn2ij85.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgljrmqkqd0jz8qn2ij85.png" alt="live searchresults"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Inside the &lt;code&gt;handleChange&lt;/code&gt; you can also fetch the data from the server. The only important thing is how will you add or reset your &lt;code&gt;results&lt;/code&gt; state. Because if you forgot to reset the &lt;code&gt;results&lt;/code&gt; state the results inside your live search container will be visible all the time.&lt;/p&gt;

&lt;h2&gt;
  
  
  Selecting Results on Key up-down
&lt;/h2&gt;

&lt;p&gt;It's nice we have our search bar where we can search and render the results. But now we need to add a keyboard event to move our selection up and down.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const SearchBar = ... =&amp;gt; {
const handleKeyDown: React.KeyboardEventHandler&amp;lt;HTMLDivElement&amp;gt; = (e) =&amp;gt; {
    const { key } = e;

    // move down
    if (key === "ArrowDown"){ }

    // move up
    if (key === "ArrowUp"){ }

   // hide search results
    if (key === "Escape"){ }

   // select the current item
    if (key === "Enter"){ }
};

return (
&amp;lt;div
      tabIndex={1}
      onKeyDown={handleKeyDown}
      className="relative outline-none"
    &amp;gt;
   &amp;lt;input ... /&amp;gt;
   ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We want to now listen to the &lt;code&gt;keyDown&lt;/code&gt; event and we are doing that to the wrapping &lt;code&gt;div&lt;/code&gt; inside &lt;code&gt;SearchBar&lt;/code&gt; component. But we can not directly listen to the &lt;code&gt;keyDown&lt;/code&gt; for divs.  So we need to use the &lt;code&gt;tabIndex&lt;/code&gt; prop. Also to avoid unwanted outlines on div focus (because we are using &lt;code&gt;tabIndex&lt;/code&gt; there will be an outline) I am using the &lt;code&gt;outline-none&lt;/code&gt; class.&lt;/p&gt;

&lt;p&gt;Let's write down the keyboard logic one by one.&lt;/p&gt;

&lt;p&gt;Handling the keyboard event is not that straightforward. Because while we are moving up or down we have to handle multiple things. Like displaying the correct UI, and scrolling in the right position if there are multiple results.&lt;/p&gt;

&lt;p&gt;So for that first, we need a state called &lt;code&gt;focusedIndex&lt;/code&gt;. As you can see the default value for this state is -1. Because later we will use this state to move our focus to the correct place. And we don't want to focus on anything at first. So -1 will work fine.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// inside SearchBar.tsx
const SearchBar = ... =&amp;gt; {
  const [focusedIndex, setFocusedIndex] = useState(-1);

...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now with the logic below it will update our focused index with the correct timing. Also if you notice I am not using -1 or +1 to update our value. Instead, we are using the &lt;code&gt;modulo&lt;/code&gt; (%) operater.&lt;/p&gt;

&lt;p&gt;This is a small formula that we can use to update our count only within the range according to the length of the results. So if you have results with the length 6 and if you press the down key then the &lt;code&gt;nextCount&lt;/code&gt; will start from 0 and goes to 5. If you press up this will be the opposite starts from 5 and goes to 0.&lt;/p&gt;

&lt;p&gt;Which is the exact value that we need to be inside the bound of the result array. If we go beyond the length we will get &lt;em&gt;index bound exception&lt;/em&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  const handleKeyDown: React.KeyboardEventHandler&amp;lt;HTMLDivElement&amp;gt; = (e) =&amp;gt; {
    let nextCount = 0;
    if (key === "ArrowDown") nextCount = (focusedIndex + 1) % results.length;

    if (key === "ArrowUp") nextCount = (focusedIndex + results.length - 1) % results.length;

    if (key === "Escape") setShowResults(false);

    if (key === "Enter") {
      e.preventDefault();
    }

    setFocusedIndex(nextCount);
  };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, there is one more thing happening. If we press the &lt;code&gt;Escape&lt;/code&gt; key we will hide the search results. But we are not handling the &lt;code&gt;Enter&lt;/code&gt; we will do that later.&lt;/p&gt;

&lt;h2&gt;
  
  
  Styling the Focused Item
&lt;/h2&gt;

&lt;p&gt;Now according to the &lt;code&gt;focusedIndex&lt;/code&gt; we need to style the result. For that, we have to take a reference of specific results and change the style.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
const SearchBar = ... =&amp;gt; {
 const resultContainer = useRef&amp;lt;HTMLDivElement&amp;gt;(null);
 return (
 ...
 {results.map((item, index) =&amp;gt; {
  return ( 
   &amp;lt;div
    ref={index === focusedIndex ? resultContainer : null}
    style={{ backgroundColor: index === focusedIndex ? "rgba(0,0,0,0.1)" : "" }}
    key={index}
    className="cursor-pointer hover:bg-black hover:bg-opacity-10 p-2"
    &amp;gt;
      {renderItem(item)}
    &amp;lt;/div&amp;gt;
    );
})}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The main thing for this &lt;code&gt;div&lt;/code&gt; is the &lt;code&gt;ref&lt;/code&gt; and the &lt;code&gt;style&lt;/code&gt; prop. What basically we are doing? If the &lt;code&gt;index&lt;/code&gt; is equal to the &lt;code&gt;focusedIndex&lt;/code&gt; we are assigning this &lt;code&gt;div&lt;/code&gt; to the &lt;code&gt;ref&lt;/code&gt; called &lt;code&gt;resultContainer&lt;/code&gt; otherwise we are making it null. Why? You will understand it later.&lt;/p&gt;

&lt;p&gt;Then we are changing the background color to black with an opacity of 10% if the &lt;code&gt;index&lt;/code&gt; is equal to the &lt;code&gt;focusedIndex&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Now with this logic, if you try to move up or down you will see the change but the results will stay in one place only. It will not scroll down or up as you update your index. To fix this use this logic.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
  useEffect(() =&amp;gt; {
    if (!resultContainer.current) return;

    resultContainer.current.scrollIntoView({
      block: "center",
    });
  }, [focusedIndex]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If there is &lt;code&gt;resultContainer&lt;/code&gt; we will use &lt;code&gt;scrollIntoView&lt;/code&gt; method to scroll in to the exact point and we will make the focused item in the center with the option &lt;code&gt;block: center&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now you should have something like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay1s60usgcdaid9ee145.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fay1s60usgcdaid9ee145.gif" alt="live search animated gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Selecting the Results
&lt;/h2&gt;

&lt;p&gt;One of the important things for live search is selecting the result so let's see how we can do that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
...
  const handleSelection = (selectedIndex: number) =&amp;gt; {
    const selectedItem = results[selectedIndex];
    if (!selectedItem) resetSearchComplete();
    onSelect &amp;amp;&amp;amp; onSelect(selectedItem);
    resetSearchComplete();
  };

  const resetSearchComplete = useCallback(() =&amp;gt; {
    setFocusedIndex(-1);
    setShowResults(false);
  }, []);
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need to now handle two things for selection first select the correct thing and send it back to the &lt;code&gt;App.tsx&lt;/code&gt;. Because this is the component where we are using it right now. Then we also need to reset the search results. &lt;/p&gt;

&lt;p&gt;For that, inside &lt;code&gt;handleSelection&lt;/code&gt; we are accepting &lt;code&gt;selectedIndex&lt;/code&gt; and extracting the selected item from inside the results array. If there is nothing just return otherwise call the &lt;code&gt;onSelect&lt;/code&gt; with the selected result. Make sure you are destructuring it from the props.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const SearchBar = ({ onSelect, ...}) =&amp;gt; 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then simply reset the states to their previous values. &lt;code&gt;focusedIndex&lt;/code&gt; to -1 and &lt;code&gt;showResults&lt;/code&gt; to false.&lt;/p&gt;

&lt;p&gt;Now we need to add this &lt;code&gt;handleSelection&lt;/code&gt; in two places. Inside Enter key press and on mouse down for the result item.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
// to select on enter
  const handleKeyDown: React.KeyboardEventHandler&amp;lt;HTMLDivElement&amp;gt; = (e) =&amp;gt; {
   ...
    if (key === "Enter") {
      e.preventDefault();
      handleSelection(focusedIndex);
    }

    setFocusedIndex(nextCount);
  };


return  (
...
{results.map((item, index) =&amp;gt; {
  return ( 
   &amp;lt;div
    onMouseDown={() =&amp;gt; handleSelection(index)}
    ref={index === focusedIndex ? resultContainer : null}
    style={{ backgroundColor: index === focusedIndex ? "rgba(0,0,0,0.1)" : "" }}
    ...
    &amp;gt;
      {renderItem(item)}
    &amp;lt;/div&amp;gt;
    );

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With this now if you try to select with a mouse or keyboard you will select the correct item. If you want to see that add &lt;code&gt;onSelect&lt;/code&gt; inside your &lt;code&gt;SearchBar&lt;/code&gt; and log the result to the console.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.tsx
const App = () =&amp;gt; {
  return (
    &amp;lt;div className="max-w-3xl mx-auto mt-10"&amp;gt;
      &amp;lt;SearchBar
        ...
        onSelect={(item) =&amp;gt; console.log(item)}
        /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Hiding Results onBlur
&lt;/h2&gt;

&lt;p&gt;Now if you are thinking why &lt;code&gt;onMouseDown&lt;/code&gt; why not &lt;code&gt;onClick&lt;/code&gt;? Instead of giving you the answer, I will show you that. &lt;/p&gt;

&lt;p&gt;Just add &lt;code&gt;onBlur&lt;/code&gt; to your top wrapper &lt;code&gt;div&lt;/code&gt; inside &lt;code&gt;SearchBar&lt;/code&gt; component. And pass &lt;code&gt;resetSearchComplete&lt;/code&gt; method to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
...
return (
    &amp;lt;div
      tabIndex={1}
      onKeyDown={handleKeyDown}
      onBlur={resetSearchComplete}
      className="relative outline-none"
    &amp;gt;
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if you click outside the search results will be gone which is the perfect result we want. Also, you will see the selected results inside your console (if you select any). But now if you change that &lt;code&gt;onMouseDown&lt;/code&gt; to &lt;code&gt;onClick&lt;/code&gt; results will be gone from the screen but you will not get the selected item inside the console.&lt;/p&gt;

&lt;p&gt;Hmmm, why is that? This is because before &lt;code&gt;onClick&lt;/code&gt; the &lt;code&gt;onBlur&lt;/code&gt; will be fired. So, &lt;code&gt;handleSelection&lt;/code&gt; will be never called.&lt;/p&gt;

&lt;h2&gt;
  
  
  Updating the value inside the search bar
&lt;/h2&gt;

&lt;p&gt;Everything looks fine here. The only thing that we need now is to display the selected profile name inside our search bar. So, create a state called &lt;code&gt;defaultValue&lt;/code&gt; inside &lt;code&gt;SearchBar.tsx&lt;/code&gt;. Then pass this value to the &lt;code&gt;input&lt;/code&gt; element.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
const SearchBar = ... ({ value }) =&amp;gt; {
  const [defaultValue, setDefaultValue] = useState("");
...
return ...
   &amp;lt;input
     ...
     value={defaultValue}
   /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you remember we are also accepting a prop called value for our &lt;code&gt;SearchBar&lt;/code&gt; component. So, if there is &lt;code&gt;value&lt;/code&gt; prop available let's assign that to the &lt;code&gt;defaultValue&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx
  useEffect(() =&amp;gt; {
    if (value) setDefaultValue(value);
  }, [value]);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if the value changes this &lt;code&gt;useEffect&lt;/code&gt; hook will update the &lt;code&gt;defaultValue&lt;/code&gt; to the &lt;code&gt;value&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let's do one more thing inside &lt;code&gt;App.tsx&lt;/code&gt;. Add a state called &lt;code&gt;selectedProfile&lt;/code&gt; and update the value inside &lt;code&gt;onSelect&lt;/code&gt;. Then pass &lt;code&gt;selectedProfile.name&lt;/code&gt; to the value &lt;code&gt;prop&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// App.tsx
const App = () =&amp;gt; {
  const [selectedProfile, setSelectedProfile] = useState&amp;lt;{ id: string; name: string }&amp;gt;();   
   return (
       ...
      &amp;lt;SearchBar
         ...
        onSelect={(item) =&amp;gt; setSelectedProfile(item)}
        value={selectedProfile?.name}
      /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now ladies and gentlemen you should see something like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftezz6cprvhzwygzsnea4.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftezz6cprvhzwygzsnea4.gif" alt="live search updating input value"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But there is one big problem. Once you have selected the result you can not make any changes to the input field.&lt;/p&gt;

&lt;p&gt;To solve this issue we have to handle the &lt;code&gt;onChange&lt;/code&gt; event directly inside our &lt;code&gt;SearchBar&lt;/code&gt; component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// SearchBar.tsx

const SearchBar = ({ onChange }) =&amp;gt; {
  ...
  type changeHandler = React.ChangeEventHandler&amp;lt;HTMLInputElement&amp;gt;;
  const handleChange: changeHandler = (e) =&amp;gt; {
    setDefaultValue(e.target.value);
    onChange &amp;amp;&amp;amp; onChange(e);
  };

return (
...
      {/* Search bar */}
      &amp;lt;input
        onChange={handleChange}
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here instead of passing &lt;code&gt;onChange&lt;/code&gt; prop directly to the &lt;code&gt;input&lt;/code&gt; element. Now we will pass &lt;code&gt;handlChange&lt;/code&gt; and inside here we will update the &lt;code&gt;defaultValue&lt;/code&gt; and then call the &lt;code&gt;onChange&lt;/code&gt; prop. With this now you can update the value with &lt;code&gt;onSelect&lt;/code&gt; and this &lt;code&gt;SearchBar&lt;/code&gt; will automatically reset the value when the &lt;code&gt;onChange&lt;/code&gt; occurs.&lt;/p&gt;

&lt;p&gt;And I think this is more than enough for this project. You can see the final look and if you have anything to say at the bottom you will find my social media links.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsm1rurh45iyqgg10f32v.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fsm1rurh45iyqgg10f32v.gif" alt="Final Live Search Result"&gt;&lt;/a&gt;&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How to Compress or Manipulate Images in React Native Expo</title>
      <dc:creator>Niraj Dhungana</dc:creator>
      <pubDate>Wed, 01 Sep 2021 03:24:43 +0000</pubDate>
      <link>https://dev.to/fsniraj/how-to-compress-or-manipulate-images-in-react-native-expo-ohi</link>
      <guid>https://dev.to/fsniraj/how-to-compress-or-manipulate-images-in-react-native-expo-ohi</guid>
      <description>&lt;p&gt;Nowadays smartphone cameras are a beast. A normal picture clicked with my smartphone becomes 4MB. And if I were just a normal user this would not be a topic of discussion but because I am a programmer it costs my cloud storage.&lt;/p&gt;

&lt;p&gt;So, in this small post I will teach you guys how we can compress the Image size in React Native Expo.&lt;/p&gt;

&lt;p&gt;For that you don’t need to do any special coding because expo has a cool &lt;code&gt;npm package&lt;/code&gt; which we can use to decrease or compress image size.&lt;/p&gt;

&lt;h2&gt;
  
  
  Which Package to Use
&lt;/h2&gt;

&lt;p&gt;Inside the expo we have an &lt;code&gt;expo-image-manipulator&lt;/code&gt; which we can use to compress image size and also for other manipulations as well like flip, rotate, crop etc. If you want more information on it then you can go to &lt;a href="https://docs.expo.dev/versions/latest/sdk/imagemanipulator/"&gt;this link&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You can also use it if you are using &lt;code&gt;bare-react-native&lt;/code&gt; cli but for that you need to go some extra miles and unfortunately I am not covering that here. You can visit &lt;a href="https://www.npmjs.com/package/expo-image-manipulator"&gt;this link&lt;/a&gt; if you are using &lt;code&gt;bare-react-native&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;First we need to install: &lt;code&gt;expo-image-manipulator&lt;/code&gt;. For that you can run this command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;expo install expo-image-manipulator
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After installing it we need to import everything as &lt;code&gt;ImageManipulator&lt;/code&gt; like below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as ImageManipulator from 'expo-image-manipulator';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const file = await ImageManipulator.manipulateAsync(img.uri, [], { compress: 0.5 });
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To manipulate images using expo-image-manipulator it provides the &lt;code&gt;manipulateAsync&lt;/code&gt; method. Which is an asynchronous method. It takes three arguments. The actual image uri goes first, actions goes second and save options at the end.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await ImageManipulator.manipulateAsync(uri, actions, saveOptions)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  What Kind of Images it Can Manipulate
&lt;/h2&gt;

&lt;p&gt;It does not take the image files from outside. So make sure you are using URI from the local file system not from the remote api link. Means you can only use the image files which you read from the device storage.&lt;/p&gt;

&lt;h2&gt;
  
  
  Actions
&lt;/h2&gt;

&lt;p&gt;Action is an array of objects representing manipulation options. We can pass multiple options as objects inside this array. Like we can &lt;strong&gt;resize, rotate, flip&lt;/strong&gt; and &lt;strong&gt;crop&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Save Options
&lt;/h2&gt;

&lt;p&gt;After manipulating the image we can also define some options and inside it we can specify the image quality and image format like png or jpg.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;await ImageManipulator.
manipulateAsync(img.uri, [
{resize: {width: 200, height: 200}},
{rotare: 45},
{flip: ImageManipulator.FlipType.Vertical}
],
{compress: 0.5, format: ImageManipulator.SaveFormat.PNG});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Inside this little example as you can see the first thing that we are passing is image uri, and some action options to resize, rotate and flip the image. And at the end we are passing save options to compressing the image by 50% and converting the image to png format.&lt;/p&gt;

&lt;p&gt;For more post like this you can check out &lt;a href="https://ndpniraj.com"&gt;this like&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>react</category>
    </item>
    <item>
      <title>React Native Multi Select on Long Press - Touchable Opacity.</title>
      <dc:creator>Niraj Dhungana</dc:creator>
      <pubDate>Sun, 29 Aug 2021 13:11:11 +0000</pubDate>
      <link>https://dev.to/fsniraj/react-native-multi-select-on-long-press-touchable-opacity-4ml1</link>
      <guid>https://dev.to/fsniraj/react-native-multi-select-on-long-press-touchable-opacity-4ml1</guid>
      <description>&lt;p&gt;Do you want to know how we can select or deselect multiple Items inside react-native. Then let’s see how we can do that using &lt;code&gt;TouchableOpacity&lt;/code&gt; and &lt;code&gt;onLongPress&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjkfo6d84c6tvambu1lj8.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjkfo6d84c6tvambu1lj8.gif" alt="react native multiple select gif"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For this project I am using bare react-native cli but it also works with expo cli as well.&lt;/p&gt;

&lt;p&gt;You can check out this same post on &lt;a href="https://ndpniraj.com/react-native-multi-select-on-long-press-touchable-opacity/" rel="noopener noreferrer"&gt;ndpniraj&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Content we will be covering in this post.
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Over view of the project&lt;/li&gt;
&lt;li&gt;Initializing Project&lt;/li&gt;
&lt;li&gt;Giving shape to our project&lt;/li&gt;
&lt;li&gt;Creating a ListItem component&lt;/li&gt;
&lt;li&gt;Adding all the logics&lt;/li&gt;
&lt;li&gt;Deselect on second tap&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Over View of the project
&lt;/h2&gt;

&lt;p&gt;Before we write any code for our react native multi select project, let’s understand what we want and how we can achieve our goal.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The feature that we want to add inside our project is that.&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If the user just taps on the list item we want to open or navigate to a different component.&lt;/li&gt;
&lt;li&gt;If the user taps and holds the finger then we want to select that list item and enable the multiple selection option.&lt;/li&gt;
&lt;li&gt;Also if the user taps outside or in an empty space we want to deselect all.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Initialize a Project
&lt;/h2&gt;

&lt;p&gt;You can initialize your project using &lt;code&gt;npx react-native init MultipleSelect&lt;/code&gt; command if you are using react-native-cli like me or you can use &lt;code&gt;expo init&lt;/code&gt; or you can use the existing react native project where you want to add this multiple select option.&lt;/p&gt;

&lt;p&gt;After initializing your project you can run it inside an emulator or inside a physical device and please don’t ask me how to do that because you are already a pro.&lt;/p&gt;

&lt;h2&gt;
  
  
  Giving Shape
&lt;/h2&gt;

&lt;p&gt;To create this multiple selection option I will be using some fake data with fake names and contact numbers. If you also want to use that you can copy from the example below (last of the page).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

...
const App = () =&amp;gt; {
  return (
    &amp;lt;Pressable&amp;gt;
      &amp;lt;FlatList
        data={data}
        renderItem={({item}) =&amp;gt;&amp;lt;Text&amp;gt;{item.name}&amp;lt;/Text&amp;gt;}
        keyExtractor={item =&amp;gt; item.id}
      /&amp;gt;
    &amp;lt;/Pressable&amp;gt;
  );
};
...


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Don’t worry bros and sis let me explain what is going on here. Here I am using the FlastList component to render our fake data and I hope you already know how it works. Like data, renderItem and all.&lt;/p&gt;

&lt;p&gt;After that the new thing is that I am wrapping the FlatList component inside this new &lt;a href="https://reactnative.dev/docs/pressable" rel="noopener noreferrer"&gt;Pressable&lt;/a&gt; component. That is because we want to deselect all the selections if we tap outside of the list. It’s like Touchable components but it's a new thing inside react-native family.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating a ListItem component
&lt;/h2&gt;

&lt;p&gt;Let’s create a beautiful component to render these list items and add some styles.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

...
const ListItem = ({item, selected, onPress, onLongPress}) =&amp;gt; (
  &amp;lt;&amp;gt;
    &amp;lt;TouchableOpacity
      onPress={onPress}
      onLongPress={onLongPress}
      style={styles.listItem}&amp;gt;
      &amp;lt;View style={{padding: 8}}&amp;gt;
        &amp;lt;Text style={{fontSize: 22, color: '#fff'}}&amp;gt;{item.name}&amp;lt;/Text&amp;gt;
        &amp;lt;Text style={{color: '#989BA1'}}&amp;gt;{item.contact}&amp;lt;/Text&amp;gt;
      &amp;lt;/View&amp;gt;
      {selected &amp;amp;&amp;amp; &amp;lt;View style={styles.overlay} /&amp;gt;}
    &amp;lt;/TouchableOpacity&amp;gt;
  &amp;lt;/&amp;gt;
);

const App = () =&amp;gt; {
  const handleOnPress = () =&amp;gt; console.log('pressed');
  const handleLongPress = () =&amp;gt; console.log('activete long press');

  return (
    &amp;lt;Pressable style={{flex: 1, padding: 15}}&amp;gt;
      &amp;lt;FlatList
        data={data}
        renderItem={({item}) =&amp;gt; (
          &amp;lt;ListItem
            onPress={handleOnPress}
            onLongPress={handleLongPress}
            item={item}
          /&amp;gt;
        )}
        keyExtractor={item =&amp;gt; item.id}
      /&amp;gt;
    &amp;lt;/Pressable&amp;gt;
  );
};
...


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we have this beautiful ListItem component to render our list items and we are using TouchableOpacity so that we can do our secret tasks. Just joking, it is here to listen to user touch events.&lt;/p&gt;

&lt;p&gt;As you can see clearly inside this ListItem component we are accepting an item, selected, onPress and onLongPress prop.&lt;/p&gt;

&lt;p&gt;Item will be the actual item with data like name and contact which we will render inside here. Selected will be the condition which we are using to display an overlay on top of our list items.&lt;/p&gt;

&lt;p&gt;This overlay is just a View component with position absolute, height and width 100% and color with half opacity. The rest of the other code is I think self explanatory.&lt;/p&gt;

&lt;p&gt;Now our project looks like this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F96zia5sbwvsqv41afx86.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F96zia5sbwvsqv41afx86.jpg" alt="react native multi select design"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we will add a state called selectedItems inside our project so that we can add the multi select options. Feel free to use any name you like.&lt;/p&gt;

&lt;p&gt;After that we will attach onPress and onLongPress prop and because we want to know which list item is currently pressed so we will use the inline function and pass the current item like here in example.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

...
 &amp;lt;FlatList
   data={data}
   renderItem={({item}) =&amp;gt; (
     &amp;lt;ListItem
     onPress={() =&amp;gt; handleOnPress(item)}
     onLongPress={() =&amp;gt; handleLongPress(item)}
     selected={getSelected(item)}     
     item={item}
     /&amp;gt;
  )}
...


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Also you may have noticed that selected={getSelected(item)}. This is to find a render that overlay if the list items are selected.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding all the logics
&lt;/h2&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

...
const App = () =&amp;gt; {
  const [selectedItems, setSelectedItems] = useState([]);

  const handleLongPress = contact =&amp;gt; {
    selectItems(contact)
  };

  const handleOnPress = contact =&amp;gt; {
    if (selectedItems.length) {
      return selectItems(contact)
    }

    // here you can add you code what do you want if user just do single tap
    console.log('pressed');
  };

  const getSelected = contact =&amp;gt; selectedItems.includes(contact.id);

  const deSelectItems = () =&amp;gt; setSelectedItems([]);

  const selectItems = (item) =&amp;gt; {
    setSelectedItems([...selectedItems, item.id]);
  }
...


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here comes the actual magic guys inside this example we have everything to select multiple items inside our react native app.&lt;/p&gt;

&lt;p&gt;First we have this &lt;code&gt;selectedItems&lt;/code&gt; state and the default value is obviously an empty array because we don’t want to select anything at the beginning.&lt;/p&gt;

&lt;p&gt;If you come to the end of this code block there we have a method called &lt;code&gt;selectItems&lt;/code&gt;. Inside this method we are just accepting an item and storing that item’s id inside the &lt;code&gt;selectedItems&lt;/code&gt; array.&lt;/p&gt;

&lt;p&gt;Then we have &lt;code&gt;handleLongPress&lt;/code&gt; and &lt;code&gt;handleOnPress&lt;/code&gt; methods as well.&lt;/p&gt;

&lt;p&gt;Inside &lt;code&gt;handleLongPress&lt;/code&gt; we are just calling the &lt;code&gt;selectItems&lt;/code&gt; method. So that is why we can remove this handleLongPress and directly use the &lt;code&gt;selectItems&lt;/code&gt; method inside &lt;code&gt;onLongPress&lt;/code&gt; prop. Which you will find inside the final code.&lt;/p&gt;

&lt;p&gt;Inside &lt;code&gt;handleOnPress&lt;/code&gt; we are checking if there are already some selected items then we are selecting more but if not then you can see that console log and the comment. You can do whatever you want.&lt;/p&gt;

&lt;p&gt;Then we have another method &lt;code&gt;getSelected&lt;/code&gt; inside this method we are just checking if the current item is already inside &lt;code&gt;selectedItems&lt;/code&gt; or not. If yes then it will return true otherwise returns false.&lt;/p&gt;

&lt;p&gt;Then we have the &lt;code&gt;deSelectItems&lt;/code&gt; and inside this method we are just resetting the value of &lt;code&gt;selectedItems&lt;/code&gt; state to an empty array. And we will attach this method to the &lt;code&gt;Pressable&lt;/code&gt; components &lt;code&gt;onPress&lt;/code&gt; prop.&lt;/p&gt;

&lt;h2&gt;
  
  
  Deselect on second tap
&lt;/h2&gt;

&lt;p&gt;With these lines of code now it will select multiple items but if you try to deselect the selected one then it will do nothing. So for that we need to update our &lt;code&gt;selectItems&lt;/code&gt; method. Like below.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

 const selectItems = item =&amp;gt; {
    if (selectedItems.includes(item.id)) {
      const newListItems = selectedItems.filter(listItem =&amp;gt; listItem !== item.id);
      return setSelectedItems([...newListItems]);
    }
    setSelectedItems([...selectedItems, item.id]);
  };


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now here we have this updated &lt;code&gt;selectItems&lt;/code&gt; method. Where we are first checking if the currently tapped item is already inside the &lt;code&gt;selectedItems&lt;/code&gt; array or not.&lt;/p&gt;

&lt;p&gt;If yes then we are removing it from the &lt;code&gt;selectedItems&lt;/code&gt; list by using array filter method and returning the code execution. If not then we are adding that list item inside our &lt;code&gt;selectedItems&lt;/code&gt; state.&lt;/p&gt;

&lt;p&gt;Now we made our final project. Multi select using react-native. Now you can use this &lt;code&gt;selectedItems&lt;/code&gt; state to render any other components if you want.&lt;/p&gt;

&lt;p&gt;Like if you want to open any options, delete icons or anything that you want you can use if there is &lt;code&gt;selectedItems.length&lt;/code&gt; then do this or that.&lt;/p&gt;

&lt;p&gt;Ok this is it for this post. Here is the complete code.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

import React, {useState} from 'react';
import {
  StyleSheet,
  FlatList,
  Pressable,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

const data = [
  {name: 'Rohan', contact: '1111111111', id: '1'},
  {name: 'Mohan', contact: '2222222222', id: '2'},
  {name: 'Sohan', contact: '3333333333', id: '3'},
  {name: 'Hohan', contact: '4444444444', id: '4'},
  {name: 'Dohan', contact: '5555555555', id: '5'},
  {name: 'Pohan', contact: '6666666666', id: '6'},
];

const ListItem = ({item, selected, onPress, onLongPress}) =&amp;gt; (
  &amp;lt;&amp;gt;
    &amp;lt;TouchableOpacity
      onPress={onPress}
      onLongPress={onLongPress}
      style={styles.listItem}&amp;gt;
      &amp;lt;View style={{padding: 8}}&amp;gt;
        &amp;lt;Text style={{fontSize: 22, color: '#fff'}}&amp;gt;{item.name}&amp;lt;/Text&amp;gt;
        &amp;lt;Text style={{color: '#989BA1'}}&amp;gt;{item.contact}&amp;lt;/Text&amp;gt;
      &amp;lt;/View&amp;gt;
      {selected &amp;amp;&amp;amp; &amp;lt;View style={styles.overlay} /&amp;gt;}
    &amp;lt;/TouchableOpacity&amp;gt;
  &amp;lt;/&amp;gt;
);

const App = () =&amp;gt; {
  const [selectedItems, setSelectedItems] = useState([]);
  const handleOnPress = contact =&amp;gt; {
    if (selectedItems.length) {
      return selectItems(contact);
    }

    // here you can add you code what do you want if user just do single tap
    console.log('pressed');
  };

  const getSelected = contact =&amp;gt; selectedItems.includes(contact.id);

  const deSelectItems = () =&amp;gt; setSelectedItems([]);

  const selectItems = item =&amp;gt; {
    if (selectedItems.includes(item.id)) {
      const newListItems = selectedItems.filter(
        listItem =&amp;gt; listItem !== item.id,
      );
      return setSelectedItems([...newListItems]);
    }
    setSelectedItems([...selectedItems, item.id]);
  };

  return (
    &amp;lt;Pressable onPress={deSelectItems} style={{flex: 1, padding: 15}}&amp;gt;
      &amp;lt;FlatList
        data={data}
        renderItem={({item}) =&amp;gt; (
          &amp;lt;ListItem
            onPress={() =&amp;gt; handleOnPress(item)}
            onLongPress={() =&amp;gt; selectItems(item)}
            selected={getSelected(item)}
            item={item}
          /&amp;gt;
        )}
        keyExtractor={item =&amp;gt; item.id}
      /&amp;gt;
    &amp;lt;/Pressable&amp;gt;
  );
};

const styles = StyleSheet.create({
  container: {},
  listItem: {
    backgroundColor: '#252628',
    marginBottom: 10,
    borderRadius: 5,
    overflow: 'hidden',
  },
  overlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%',
    backgroundColor: 'rgba(255,0,0,0.5)',
  },
});

export default App;


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
    </item>
    <item>
      <title>React Native How to Find-out Which Key is Being Pressed</title>
      <dc:creator>Niraj Dhungana</dc:creator>
      <pubDate>Sat, 22 May 2021 06:23:59 +0000</pubDate>
      <link>https://dev.to/fsniraj/react-native-how-to-find-out-which-key-is-being-pressed-1g35</link>
      <guid>https://dev.to/fsniraj/react-native-how-to-find-out-which-key-is-being-pressed-1g35</guid>
      <description>&lt;p&gt;Recently I was working on a React Native project and inside that project I wanted to track which key was being pressed. I didn't want to track every key press, but in particular I wanted to track "backspace".&lt;/p&gt;

&lt;p&gt;If you go to &lt;a href="https://reactnative.dev/"&gt;React Native’s official documentation&lt;/a&gt; and search for TextInput then there are lots of props which we can use inside TextInput. But most of us don't care about those props. There are more than 40 to 50 props which we can use inside the TextInput component.&lt;/p&gt;

&lt;p&gt;So, in this post I am sharing my experience with you on how I tracked which key is being pressed and which prop I used.&lt;/p&gt;

&lt;h2&gt;
  
  
  The prop to find out which key is being pressed
&lt;/h2&gt;

&lt;p&gt;There is a prop called onKeyPress which we can use to track which key is being pressed inside the React Native TextInput component.&lt;/p&gt;

&lt;p&gt;If you are already familiar with DOM manipulation using vanilla javascript. Then this prop works the same as key press events. The only difference is, inside DOM we would get key code but here you will get the exact key value as string.&lt;/p&gt;

&lt;h2&gt;
  
  
  How it works
&lt;/h2&gt;

&lt;p&gt;You can simply use &lt;a href="https://reactnative.dev/docs/textinput#onkeypress"&gt;onKeyPress&lt;/a&gt; prop like onChangeText prop inside TextInput component. It's a callback function like we can pass inside onChangeText prop.&lt;/p&gt;

&lt;p&gt;But inside this callback you will get an object. From that object we can destructure nativeEvent and inside that nativeEvent object we will get key information.&lt;/p&gt;

&lt;p&gt;Let’s see that in action.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;&amp;lt;TextInput onKeyPress={ ({nativeEvent}) =&amp;gt; console.log(nativeEvent.key) /&amp;gt;&lt;/code&gt;&lt;/p&gt;

</description>
      <category>reactnative</category>
      <category>expo</category>
    </item>
  </channel>
</rss>
