<?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>Forem: Niya Panamdanam</title>
    <description>The latest articles on Forem by Niya Panamdanam (@findniya).</description>
    <link>https://forem.com/findniya</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%2F442658%2F83c50b50-05e9-4c3b-b564-e58f7d3fe428.jpeg</url>
      <title>Forem: Niya Panamdanam</title>
      <link>https://forem.com/findniya</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/findniya"/>
    <language>en</language>
    <item>
      <title>The OR operator (||) vs Nullish Coalescing (??)</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Tue, 25 Apr 2023 13:57:44 +0000</pubDate>
      <link>https://forem.com/findniya/the-or-operator-vs-nullish-coalescing--agp</link>
      <guid>https://forem.com/findniya/the-or-operator-vs-nullish-coalescing--agp</guid>
      <description>&lt;p&gt;You may have seen OR operator &lt;code&gt;||&lt;/code&gt; used commonly to handle default values. But, there is also the less known nullish coalescing operator &lt;code&gt;??&lt;/code&gt; that can also help with handling default values. Though similar, there are some key deferences between the two.&lt;/p&gt;

&lt;p&gt;The OR operator &lt;code&gt;||&lt;/code&gt; returns the first &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy"&gt;truthy &lt;/a&gt; value in a series of expressions. If all expressions evaluate to &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy"&gt;falsy&lt;/a&gt; values, the final expression is returned. This means that the OR operator will return the second expression if the first expression is falsy, even if the second expression is also falsy.&lt;/p&gt;

&lt;p&gt;For example, consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const x = 0 || false;
console.log(x); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the OR operator returns the second expression &lt;code&gt;false&lt;/code&gt; because the first expression &lt;code&gt;0&lt;/code&gt; is falsy.&lt;/p&gt;

&lt;p&gt;The nullish coalescing operator (??) returns the first defined value in a series of expressions. If the first expression is null or undefined, the second expression is returned. This means that the nullish coalescing operator will only return the second expression if the first expression is null or undefined.&lt;/p&gt;

&lt;p&gt;For example, consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const y = null ?? 'default';
console.log(y); // 'default'
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the nullish coalescing operator returns the second expression &lt;code&gt;default&lt;/code&gt; because the first expression &lt;code&gt;null&lt;/code&gt; is nullish.&lt;/p&gt;

&lt;p&gt;One of the key differences between these two operators is how they handle falsy values. The OR operator considers any falsy value (e.g. 0, '', false) to be equivalent to false, while the nullish coalescing operator only considers &lt;code&gt;null&lt;/code&gt; and &lt;code&gt;undefined&lt;/code&gt; to be nullish.&lt;/p&gt;

&lt;p&gt;For example, consider the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const z = '' || 'default';
console.log(z); // 'default'

const w = '' ?? 'default';
console.log(w); // ''

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

&lt;/div&gt;



&lt;p&gt;In this case, the OR operator returns the second expression &lt;code&gt;'default'&lt;/code&gt; because the first expression &lt;code&gt;''&lt;/code&gt; is falsy, while the nullish coalescing operator returns the first expression &lt;code&gt;''&lt;/code&gt; because it is not nullish.&lt;/p&gt;

&lt;p&gt;In general, developers should use the nullish coalescing operator when they want to specifically check for null or undefined values, and the OR operator when they want to handle any falsy value. However, it's important to consider the context in which these operators are being used and choose the one for your specific use case.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>codequality</category>
      <category>webdev</category>
    </item>
    <item>
      <title>useImperativeHandle React Hook</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Sun, 11 Dec 2022 19:12:48 +0000</pubDate>
      <link>https://forem.com/findniya/useimperativehandle-react-hook-3kd2</link>
      <guid>https://forem.com/findniya/useimperativehandle-react-hook-3kd2</guid>
      <description>&lt;p&gt;&lt;code&gt;useImperativeHandle&lt;/code&gt; is a React hook that allows a child component to expose an imperative API to a parent component. "Imperative" here refers to a direct order or command.&lt;/p&gt;

&lt;p&gt;To use imperative handle, the child component must call &lt;code&gt;useImperativeHandle&lt;/code&gt; in its render method and pass in a reference to the parent component. The child can then define the imperative API by returning an object from the &lt;code&gt;useImperativeHandle&lt;/code&gt; call. The parent can access this API by using the ref prop on the child component.&lt;/p&gt;

&lt;p&gt;Here is an example of how to use &lt;code&gt;useImperativeHandle&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;// Child component
const Modal = ({forwardedRef}) =&amp;gt; {
  const [isOpen, setIsOpen] = useState(false)
  useImperativeHandle(forwardedRef, () =&amp;gt; ({
    open: () =&amp;gt; {
      setIsOpen(true);
    },
    close: () =&amp;gt; {
      setIsOpen(false);
    }
  }))

  return (
     &amp;lt;div&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; setIsOpen(false)}&amp;gt;Close&amp;lt;/button&amp;gt;
      &amp;lt;p&amp;gt;Modal content&amp;lt;/p&amp;gt;
    &amp;lt;/div&amp;gt;
   )
}
export default forwardRef(Modal)

// Parent component
const App = () =&amp;gt;{
  const modalRef = useRef(null);

  const handleOpen = () =&amp;gt; {
    modalRef.current.open();
  }

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;p&amp;gt;Parent&amp;lt;/p&amp;gt;
      &amp;lt;Modal forwardedRef={modalRef}/&amp;gt;
      &amp;lt;button onClick={handleOpen}&amp;gt;Open&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, the &lt;code&gt;Modal&lt;/code&gt; component uses &lt;code&gt;useImperativeHandle&lt;/code&gt; to define an imperative API for the parent &lt;code&gt;App&lt;/code&gt; component to use. The &lt;code&gt;App&lt;/code&gt; component can now use the ref prop to open the &lt;code&gt;Modal&lt;/code&gt; component. This allows the &lt;code&gt;App&lt;/code&gt; component to control the state of the &lt;code&gt;Modal&lt;/code&gt; component without re-rendering the whole parent component.&lt;/p&gt;

&lt;p&gt;One example of where this might be useful is when you have a custom input component that needs to be controlled by a parent form. The input component might have internal state for managing focus, selection, and other aspects of user interaction. The parent form can use imperative handle to access this state and update the input as necessary, and not worry about every other child component in the parent component re-rendering with the form changes.&lt;/p&gt;

&lt;p&gt;Another example is when you have a complex animation or transition that is implemented in a child component. The parent can use imperative handle to trigger the animation or transition and control its behavior. This allows the parent to have full control over the animation without having to know the details of how it is implemented in the child.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;useImperativeHandle&lt;/code&gt; is a useful tool for creating reusable components that can be easily integrated into a parent component. It allows the child to expose a specific API to the parent, while keeping its internal implementation hidden. This helps to maintain the separation of concerns between the child and parent.&lt;/p&gt;

</description>
      <category>gratitude</category>
    </item>
    <item>
      <title>Using .env with React &amp; Node</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Wed, 16 Nov 2022 15:00:00 +0000</pubDate>
      <link>https://forem.com/findniya/using-env-with-react-node-4591</link>
      <guid>https://forem.com/findniya/using-env-with-react-node-4591</guid>
      <description>&lt;p&gt;_NOTE: This article was originally written on Oct, 2018.&lt;/p&gt;

&lt;p&gt;In this article, I’m assuming you have heard of environment variables and may have even seen &lt;code&gt;process.env&lt;/code&gt; in some places of your code. If not read this: &lt;a href="https://codeburst.io/process-env-what-it-is-and-why-when-how-to-use-it-effectively-505d0b2831e7"&gt;“process.env: What it is and why/when/how to use it effectively”&lt;/a&gt;. The article is a great explainer and gives a really detailed idea on why it’s important to use environment variables.&lt;/p&gt;

&lt;p&gt;My application is a single repo app using a Node backend and a React front end. You can find it here: &lt;a href="https://github.com/np6176a/feedMe"&gt;https://github.com/np6176a/feedMe&lt;/a&gt;. This means for my project I have two .env files, one for the Node instance and the other for the React instance. FYI for the beginners, you won’t see my .env files in github. In fact you should not ever commit your .env file to GitHub repo and should keep it in .gitignore. This is where you keep your secret keys that you don’t want anyone else using.&lt;/p&gt;

&lt;p&gt;The directory structure in my case with the .env files looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-feedMe
|_  .gitignore
|_  —client
    |_ .env
|_  -server
    |_ server.js
    |_ .env
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you initiated your React app with either Next.Js or Create React App you don’t need any other packages to get going. You can just start by creating your &lt;code&gt;.env&lt;/code&gt; file in the root directory of the React App. Then for each key make sure to name it with &lt;code&gt;REACT_APP_&lt;/code&gt; before your key name. So your key name would be &lt;code&gt;REACT_APP_KEY_NAME&lt;/code&gt;. The &lt;code&gt;REACT_APP_&lt;/code&gt; is necessary for both Next.Js and Create React App to recognize the key. An example of this use case is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;#Declaring your Secret Key in your .env file
$ REACT_APP_API_KEY = exampleAPIKEY

#Using the above key in code
const apiKey = process.env.REACT_APP_API_KEY
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For the Node instance you need to first install dotenv node package in your root directory, in my case in the feedme directory.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ yarn add dotenv
#or
$ npm install dotenv --save
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then create the &lt;code&gt;.env&lt;/code&gt; file inside the directory you have your initial &lt;code&gt;index.js&lt;/code&gt; or &lt;code&gt;server.js&lt;/code&gt; file that run your Node app. In my case this was inside my server directory. Then define your keys inside the &lt;code&gt;.env&lt;/code&gt; file &lt;code&gt;MY_KEY=myexampleAPIkey&lt;/code&gt;. You can now use it anywhere in your Node App like so: &lt;code&gt;process.env.MY_KEY&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The above is a very basic rundown on how to start using environment variables for either Node or React applications. Here are some other articles that I found super helpful when learning about environment variables:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5"&gt;Using environment variables in React: https://medium.com/@trekinbami/using-environment-variables-in-react-6b0a99d83cf5&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://daveceddia.com/multiple-environments-with-react/"&gt;Using React in Multiple Environments (My favorite): https://daveceddia.com/multiple-environments-with-react/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f"&gt;Using dotenv : https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://codeburst.io/process-env-what-it-is-and-why-when-how-to-use-it-effectively-505d0b2831e7"&gt;process.env What it is and why/when/how to use it effectively: https://codeburst.io/process-env-what-it-is-and-why-when-how-to-use-it-effectively-505d0b2831e7&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>react</category>
      <category>node</category>
    </item>
    <item>
      <title>JavaScript Debugging</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Mon, 14 Nov 2022 13:00:00 +0000</pubDate>
      <link>https://forem.com/findniya/javascript-debugging-2dli</link>
      <guid>https://forem.com/findniya/javascript-debugging-2dli</guid>
      <description>&lt;p&gt;Debugging javascript can be a frustrating task. In this article I have outlined three ways to help you better debug.&lt;/p&gt;

&lt;p&gt;First thing is to open up your dev tools in whatever browser you are using. You can do this by either right clicking and selecting inspect, or the keyboard shortcut Cmd + Opt + I on a mac. You can also press F12 which will open you dev tool with the Console tab in focus. The dev tools in your browser is your interface into seeing how your code is executing in the browser.&lt;/p&gt;

&lt;p&gt;For the purposes of this article I’m going to focus on using Chrome and the Chrome dev tools.&lt;/p&gt;

&lt;h2&gt;
  
  
  Method 1: &lt;code&gt;console.log()&lt;/code&gt;
&lt;/h2&gt;

&lt;p&gt;The most commonly known Javascript debug method is &lt;code&gt;console.log()&lt;/code&gt;. The log method writes a message directly to the console. You can use this to print the values of your javascript variables.&lt;br&gt;
&lt;/p&gt;
&lt;div&gt;
  &lt;iframe src="https://loom.com/embed/bc51f8f8184248a9a7873b3ea33b737a"&gt;
  &lt;/iframe&gt;
&lt;/div&gt;







&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const myFunction = () =&amp;gt; {
    // print the value of x with a string label 'x'
    console.log('x', x)

    const number  = myMathFunction(x)
    // print the value of number with a label 'number'
    console.log('number', number)

    const numberPercentage = formatAsPercent(number)
    // print the value of number with a label 'number'
    console.log('numberPercentage', numberPercentage)

    // print my fun string
    console.log('You can just type Hello!!!')

    return numberPercentage

}

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

&lt;/div&gt;


&lt;p&gt;In addition to printing your variable value to the console, you can add a little string to name your variable in the console.&lt;/p&gt;

&lt;p&gt;You can read more on the console.log() method here &lt;a href="https://www.w3schools.com/jsref/met_console_log.asp"&gt;https://www.w3schools.com/jsref/met_console_log.asp&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Method 2: Breakpoints
&lt;/h2&gt;

&lt;p&gt;You can set breakpoints for your Javascript code in your dev tools. You can do this in Chrome &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Go to the Source tab in your Inspect.&lt;/li&gt;
&lt;li&gt;Navigate to the your Javascript file and the code.&lt;/li&gt;
&lt;li&gt;Then click on the line of code number that is to the left of your code. This will add a break point in your browser for that line of code, so when you refresh it will pause your code on that line.&lt;/li&gt;
&lt;li&gt;You the press the play button to have your code continue running.&lt;/li&gt;
&lt;/ul&gt;


&lt;div&gt;
  &lt;iframe src="https://loom.com/embed/923509370651492b823569fffe18d28c"&gt;
  &lt;/iframe&gt;
&lt;/div&gt;






&lt;p&gt;As you can see in the video while the code is stopped at the breakpoint, you can use the console to show you the value of your variables. In some cases you can also hover over the variable in the lines of your code to see a tooltip display with the value.&lt;/p&gt;

&lt;p&gt;Chrome also does a cool thing by letting you add conditional breakpoints. You can read more about that and line break points here &lt;a href="https://developer.chrome.com/docs/devtools/javascript/breakpoints/"&gt;https://developer.chrome.com/docs/devtools/javascript/breakpoints/&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Method 3: Debugger (my fav &amp;lt;3)
&lt;/h2&gt;

&lt;p&gt;The last method is actually adding debugger to your code in your editor. This adds breakpoints to your code no matter which browser you use. You just need the dev tools for your browser open and as the code runs it will stop at the line you added the &lt;code&gt;debugger&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;const myFunction = () =&amp;gt; {
     const number  = myMathFunction(x)
     debugger

     const numberPercentage = formatAsPercent(number)
     debugger

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

&lt;/div&gt;

&lt;h2&gt;
  
  
  &lt;div&gt;
  &lt;iframe src="https://loom.com/embed/6f3220670dfd4ede9922665957c97590"&gt;
  &lt;/iframe&gt;
&lt;/div&gt;

&lt;/h2&gt;


&lt;p&gt;As you can see in the video the code stops at the lines with debugger. You can press the play button in your dev tools to continue running your code. The debugger behaves exactly as it would if you had added breakpoints in the Chrome dev tools.&lt;/p&gt;

&lt;p&gt;You can also see that beyond just printing my variable value, in the above example I also called my function &lt;code&gt;formatAsPercent()&lt;/code&gt; directly in the console. As long as the debugger is set after you have defined your function you can then call that function in the console. You can also call other native Javascript methods like &lt;code&gt;.map()&lt;/code&gt; or &lt;code&gt;.filter()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The reason I personally love this method is that when working with Javascript frameworks like React this is a more reliable way of pausing my code at every re-render. &lt;code&gt;console.logs()&lt;/code&gt; can print way too many times sometimes when React re-renders a component multiple times too quickly. This makes it harder to clearly notice a difference in the variable values or figure out when exactly the value changed.&lt;/p&gt;

&lt;p&gt;The debugger stops the code at on that line every time the code is re-run. It will pause on every re-render of that component. This means on every re-render I can be sure my variables have the correct values and know when my variable has changed. I can also quickly test out different Javascript methods on my variable directly in the console before committing to my code in my editor.&lt;/p&gt;

&lt;p&gt;You can read more about the debugger method here &lt;a href="https://www.w3schools.com/js/js_debugging.asp"&gt;https://www.w3schools.com/js/js_debugging.asp&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;With the above methods debugging in Javascript can be a less frustrating experience. Happy debugging!&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Integrate React Hook Forms with Existing Form Components</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Thu, 03 Jun 2021 03:09:09 +0000</pubDate>
      <link>https://forem.com/findniya/integrate-react-hook-forms-with-existing-form-components-46ga</link>
      <guid>https://forem.com/findniya/integrate-react-hook-forms-with-existing-form-components-46ga</guid>
      <description>&lt;p&gt;React Hook Form is a form handler that handles validation, error, etc using hooks. The library also has great integration with Typescript. You can read more about the it here: &lt;a href="https://react-hook-form.com/"&gt;React Hook Form&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I found the best part of the library is the ease of integrating it into existing legacy code with minimal adjustments.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;&lt;a href="https://react-hook-form.com/get-started"&gt;Get Started&lt;/a&gt;&lt;/em&gt; documentation will walk you through how to use the &lt;code&gt;useForm&lt;/code&gt; hook and &lt;code&gt;register&lt;/code&gt; option for form elements. This is a great option if you are not using third-party form elements like React Select, Antd, Material UI, or legacy custom form element components.&lt;/p&gt;

&lt;p&gt;For our sample case, I have the following &lt;code&gt;UserProfile.jsx&lt;/code&gt; component, with a custom input component.&lt;/p&gt;

&lt;h3&gt;
  
  
  UserProfile.jsx
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const UserProfile = () =&amp;gt;{

 const [userName, setUserName] = useState('')
 const [email, setEmail] = useState('')

const onSubmit = async()=&amp;gt; {
  await axios.post('/user',{userName, email})
    .then(()=&amp;gt;console.log('Success'))
    .catch((e)=&amp;gt; console.error(e))
}

 return (
  &amp;lt;div&amp;gt;
    &amp;lt;CustomInput 
      type='text'
      label='User Name'
      name='userName' 
      value={userName} 
      onChange={setUserName}
    /&amp;gt;
    &amp;lt;CustomInput 
      type='text'
      label='Email'
      name='email' 
      value={email} 
      onChange={setEmail}
    /&amp;gt;
    &amp;lt;button onClick={onSubmit}&amp;gt;
     Submit
    &amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
 )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  The &lt;code&gt;CustomInput.jsx&lt;/code&gt; component:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const CustomInput = (
  {
    name,
    type = 'text',
    label,
    disabled = false,
    value,
    onChange,
  },
) =&amp;gt; {
return (
    &amp;lt;&amp;gt;
        &amp;lt;label htmlFor={name}&amp;gt;{label}&amp;lt;/labe&amp;gt;
        &amp;lt;input
          value={value}
          onChange={(v) =&amp;gt; onChange(v.target.value)}
          type={type}
          disabled={disabled}
        /&amp;gt;
    &amp;lt;/&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the cases of the third-party libraries, React Hook Form recommends we use the &lt;code&gt;Controller&lt;/code&gt; component to wrap the third-party component. You can read more about it here: &lt;a href="https://react-hook-form.com/api/usecontroller/controller"&gt;Controller&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can use the same &lt;code&gt;Controller&lt;/code&gt; functionality through the &lt;code&gt;useController&lt;/code&gt; hook to update &lt;code&gt;CustomInput.jsx&lt;/code&gt; component.&lt;/p&gt;

&lt;h3&gt;
  
  
  Updated &lt;code&gt;CustomInput.jsx&lt;/code&gt;
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const CustomInput = (
  {
    name,
    type = 'text',
    label,
    disabled = false,
    controller,
    rules /**A way to set input validation**/
  },
) =&amp;gt; {

const { field } = useController({
      name, /**This is the unique identifier used by React Hook Form**/
      rules,
      control,
    })

return (
    &amp;lt;&amp;gt;
      &amp;lt;label htmlFor={name}&amp;gt;{label}&amp;lt;/label&amp;gt;
      &amp;lt;div&amp;gt;
        &amp;lt;input
           {...field} /**this allows React Hook Form to handle the value, onChange and other form functionalities**/
          type={type}
          disabled={disabled}
        /&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every time the &lt;code&gt;CustomInput&lt;/code&gt; component is used it will require the &lt;code&gt;controller&lt;/code&gt; prop. Now we modify the parent &lt;code&gt;UserProfile.jsx&lt;/code&gt; component to use &lt;code&gt;useForm&lt;/code&gt; hook and pass in the &lt;code&gt;controller&lt;/code&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use &lt;code&gt;useForm&lt;/code&gt; Hook
&lt;/h3&gt;

&lt;p&gt;First we remove the &lt;code&gt;useState&lt;/code&gt; hook and use the &lt;code&gt;useForm&lt;/code&gt; hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const {controller, handleSubmit} = useForm({
  defaultValues:{
    userName:'',
    email: '',
  }
 })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update the props
&lt;/h3&gt;

&lt;p&gt;Then update the props passed into the &lt;code&gt;CustomInput&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;&amp;lt;CustomInput 
      type='text'
      label='User Name'
      name='userName' 
      controller={controller}
      rules={{ required: true}} /** passing in the validation rule**/
    /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update the button
&lt;/h3&gt;

&lt;p&gt;Next we need to update the &lt;code&gt;button&lt;/code&gt; to trigger the &lt;code&gt;handleSubmit&lt;/code&gt; from the &lt;code&gt;useForm&lt;/code&gt; hooks. This will allow us to use the validated form data in our &lt;code&gt;onSubmit&lt;/code&gt; function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;button 
  onClick={handleSubmit(
    (data)=&amp;gt;onSubmit(data)
   )}
&amp;gt;
  Submit
&amp;lt;/button&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Update onSubmit
&lt;/h3&gt;

&lt;p&gt;Last we need to update the &lt;code&gt;onSubmit&lt;/code&gt; function to use the correct &lt;code&gt;data&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;const onSubmit = async(data) =&amp;gt; {
  await axios.post('/user',{
      userName:data.userName, 
      email:data.email
    })
    .then(()=&amp;gt;console.log('Success'))
    .catch((e)=&amp;gt; console.error(e))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our final &lt;code&gt;UserProfile.jsx&lt;/code&gt; component looks as follows:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const UserProfile = () =&amp;gt;{

/**Removed state and replaced it with useForm**/
 const {controller, handleSubmit} = useForm({
  defaultValues:{
    userName:'',
    email: '',
  }
 })

/**Updated the submit function to get validated data from the useForm hook**/
const onSubmit = async(data) =&amp;gt; {
  await axios.post('/user',{
      userName:data.userName, 
      email:data.email
    })
    .then(()=&amp;gt;console.log('Success'))
    .catch((e)=&amp;gt; console.error(e))
}

 return (
  &amp;lt;div&amp;gt;
    &amp;lt;CustomInput 
      type='text'
      label='User Name'
      name='userName' 
      controller={controller}
      rules={{ required: true}} /** passing in the validation rule**/
    /&amp;gt;
    &amp;lt;CustomInput 
      type='text'
      label='Email'
      name='email' 
      controller={controller}
      rules={{ required: true}}
    /&amp;gt;
    &amp;lt;button 
      onClick={handleSubmit((data)=&amp;gt;onSubmit(data))} /**the data passes in the validated input values to the submit function**/
    &amp;gt;
     Submit
    &amp;lt;/button&amp;gt;
  &amp;lt;/div&amp;gt;
 )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;With these changes we can continue to use existing form elements, and integrate the powerful tools of React Hook Forms with minimal changes.&lt;/p&gt;

</description>
      <category>codequality</category>
      <category>react</category>
      <category>javascript</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Using Custom Events to communicate between legacy jQuery code and new Framework code</title>
      <dc:creator>Niya Panamdanam</dc:creator>
      <pubDate>Wed, 02 Jun 2021 17:52:13 +0000</pubDate>
      <link>https://forem.com/findniya/using-custom-events-to-communicate-between-legacy-jquery-code-and-new-framework-code-1kof</link>
      <guid>https://forem.com/findniya/using-custom-events-to-communicate-between-legacy-jquery-code-and-new-framework-code-1kof</guid>
      <description>&lt;p&gt;&lt;em&gt;This is an updated version of one my older blogs: &lt;a href="https://medium.com/@findniya/using-custom-events-to-communicate-between-legacy-jquery-code-and-new-framework-code-e34bb725c734"&gt;Old Post&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;While writing a new feature using React one of my hurdles was figuring out a way to make the new React code and the old jQuery code communicate with each other. My new component, had to get date and time from the date picker written in jQuery code as users interacted with it. At this time I didn’t have the option to rewrite the date picker in React.&lt;/p&gt;

&lt;p&gt;My solution to this problem was to use Custom Events.&lt;br&gt;
The custom event was setup in the jQuery function to dispatch every time it returned a result. Then I setup the React component to listen for this custom event and update state.&lt;/p&gt;
&lt;h3&gt;
  
  
  Let’s Look At Some Code Samples
&lt;/h3&gt;

&lt;p&gt;&lt;strong&gt;The React Component:&lt;/strong&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 MyComponent ()=&amp;gt; {
    const [dateRange, setDateRange] = useState({from:'', to:''})

    return &amp;lt;div id='containerId' /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This component renders a div with an id that I will need for the jQuery to use. My state object has the keys from and to that needs the date and time information from the jQuery date picker.&lt;/p&gt;

&lt;h3&gt;
  
  
  Part of jQuery Code handling the DatePicker:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setDateTime: function() {
  var from = moment(picker.from).utcOffset(this.utcOffset());
  var to = moment(picker.to).utcOffset(this.utcOffset());

  this.setView(from, to);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above snippet is the small part of a larger file using global variables to trigger the &lt;code&gt;setDateTime&lt;/code&gt; function. This then passes the &lt;code&gt;from&lt;/code&gt; and &lt;code&gt;to&lt;/code&gt; values to other functions in the jQuery file. Functionally the jQuery date picker works well, code wise though its super fragile and impossibly hard to figure how it all connects.&lt;/p&gt;

&lt;p&gt;Thankfully the above snippet is all I needed. Every time the &lt;code&gt;setDateTime&lt;/code&gt; function was triggered I need it to send the &lt;code&gt;from&lt;/code&gt; and &lt;code&gt;to&lt;/code&gt; values to my React component.&lt;/p&gt;

&lt;h3&gt;
  
  
  Adding my custom event:
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setDateTime: function() {
  var from = moment(picker.from).utcOffset(this.utcOffset());
  var to = moment(picker.to).utcOffset(this.utcOffset());
  var myEvent = new CustomEvent('dateTimeEvent', 
      { bubbles: true, detail: { dateTime: {from, to} });

    document.querySelector('#containerId').dispatchEvent(myEvent);
  this.setView(from, to);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As the &lt;code&gt;from&lt;/code&gt; and &lt;code&gt;to&lt;/code&gt; are set in the setDateTime function, I have my custom event named myEvent that then bubbles the dateTime object with these values. The event is dispatched to the &lt;code&gt;div&lt;/code&gt; with the &lt;code&gt;id='containerId'&lt;/code&gt; in my React component. This function does not in any way interfere with the rest of the jQuery code. It just passes the information I need without changing any other existing functionality.&lt;/p&gt;

&lt;h3&gt;
  
  
  Update the React Component
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(()=&amp;gt;{
  window.addEventListener('dateTimeEvent', 
  onDateTimeChange(e))
},[])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I added the event listener to the &lt;code&gt;useEffect&lt;/code&gt;. Any time the &lt;code&gt;setDateTime&lt;/code&gt; function in the jQuery is triggered the listener will capture &lt;code&gt;dateTime&lt;/code&gt; object and pass it into my function &lt;code&gt;onDateTimeChange&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;const onDateTimeChange = (e) =&amp;gt; {
   setDateRange({
      from: e.detail.dateTime.from,
      to: e.detail.dateTime.to
   })
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every time the &lt;code&gt;onDateTimeChange&lt;/code&gt; is triggered it updates state in my React component with the date time value from the jQuery code.&lt;/p&gt;

&lt;p&gt;In this way my new React component could coexist with the jQuery date picker without having to worry about the legacy code interfering. Plus the changes to the jQuery code were minimal and didn’t affect any of its existing functions.&lt;/p&gt;

&lt;h3&gt;
  
  
  What The React Component Looks Like Now
&lt;/h3&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const MyComponent ()=&amp;gt; {
    const [dateRange, setDateRange] = useState({from:'', to:''})

const onDateTimeChange = (e) =&amp;gt; {
   setDateRange({
      from: e.detail.dateTime.from,
      to: e.detail.dateTime.to
   })
}

useEffect(()=&amp;gt;{
  window.addEventListener('dateTimeEvent', 
  onDateTimeChange(e))
},[])

    return &amp;lt;div id='containerId' /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was an interim solution that allowed me to continue working on the new feature, without having to do a costly rewrite at the same time.&lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>legacycode</category>
      <category>codequality</category>
    </item>
  </channel>
</rss>
