{"id":4934,"date":"2024-08-22T16:10:47","date_gmt":"2024-08-22T10:40:47","guid":{"rendered":"https:\/\/namastedev.com\/blog\/?p=4934"},"modified":"2024-08-22T16:10:47","modified_gmt":"2024-08-22T10:40:47","slug":"mastering-useref-and-forwardref-in-react-a-comprehensive-guide-to-reusable-component-flexibility","status":"publish","type":"post","link":"https:\/\/namastedev.com\/blog\/mastering-useref-and-forwardref-in-react-a-comprehensive-guide-to-reusable-component-flexibility\/","title":{"rendered":"Mastering useRef and forwardRef in React: A Comprehensive Guide to reusable Component Flexibility"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><span class=\"ql-size-large\">This React login component serves as a solid foundation for building authentication interfaces in modern web applications. It demonstrates how to handle to create <\/span><strong class=\"ql-size-large\"><u>reusable UI elements<\/u>, <u>useState<\/u>, <u>useRef<\/u>, <u>controlled components<\/u>, <u>prop forwarding<\/u>, <u>forwardRef<\/u> and <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong class=\"ql-size-large\"><u>manage form inputs<\/u>, <u>perform validation<\/u> <\/strong><span class=\"ql-size-large\">and <\/span><u class=\"ql-size-large\">use component composition<\/u><span class=\"ql-size-large\"> to create reusable UI elements. By understanding and implementing these concepts, you can create robust and user-friendly forms that are both maintainable and scalable. Whether you&#8217;re working on a small project or a large enterprise application, mastering these techniques will significantly improve your development workflow.<\/span><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">1. Component Structure Overview<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\"><strong class=\"ql-size-large\">Login.js<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import { useRef, useState } from \"react\"\nimport Header from \".\/Header\"\nimport { checkValidate } from \"..\/utils\/validate\"\nimport InputText from \".\/InputText\"\n\nconst Login = () =&gt; {\n&nbsp; &nbsp; const [isSignInForm, setIsSignInForm] = useState(true)\n&nbsp; &nbsp; const [errorMessage, setErrorMessage] = useState(true)\n\n&nbsp; &nbsp; const email = useRef(null)&nbsp; &nbsp; \n    const password = useRef(null)\n&nbsp; &nbsp; const firstName = useRef(null)\n\n&nbsp; &nbsp; const handleButtonClick = () =&gt; {&nbsp; &nbsp; &nbsp; &nbsp;       \n    setErrorMessage(checkValidate(email.current.value,password.current.value))&nbsp; &nbsp; \n    }\n\n&nbsp; &nbsp; const toggleSignInForm = () =&gt; {&nbsp; &nbsp; &nbsp; &nbsp; \n     setIsSignInForm(!isSignInForm)&nbsp; &nbsp; \n    }\n&nbsp; \nreturn (&nbsp; &nbsp;\n &lt;div&gt;&nbsp;\n&nbsp; &lt;form onSubmit={(e) =&gt; e.preventDefault()} &gt;&nbsp; &nbsp; &nbsp; &nbsp; \n   &lt;h1&gt;{isSignInForm ? \"Sign In\" : \"Sign Up\"}&lt;\/h1&gt;&nbsp;\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n    {!isSignInForm &amp;&amp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \n     &lt;InputText placeholder={\"First name\"} ref={firstName} \/&gt;&nbsp; &nbsp; &nbsp; &nbsp; \n     )}&nbsp; &nbsp; \n&nbsp; &nbsp; \n    &lt;InputText placeholder={\"Name\"} ref={email} \/&gt;\n&nbsp; &nbsp; &lt;InputText placeholder={\"Password\"} ref={password} \/&gt;\n\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;button  onClick={handleButtonClick}&gt;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;\n         {isSignInForm ? \"Sign In\" : \"Sign Up\"}&nbsp; &nbsp; &nbsp; &nbsp; \n        &lt;\/button&gt;\n\n&nbsp; &nbsp; &nbsp; &nbsp; &lt;p&gt;{errorMessage}&lt;\/p&gt;&nbsp; &nbsp; &nbsp; &nbsp;\n        &lt;p onClick={toggleSignInForm}&gt;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \n         &lt;span&gt;New to netflix?&lt;\/span&gt;\n &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {isSignInForm ? \"SignUp Now\" : \"SignIn Now\"}&nbsp; &nbsp; &nbsp; &nbsp; \n        &lt;\/p&gt;&nbsp; &nbsp; &nbsp;\n    &lt;\/form&gt;&nbsp; &nbsp; \n &lt;\/div&gt;&nbsp; \n)}\nexport default Login\n\n<\/pre>\n\n\n\n<h1 class=\"wp-block-heading\">2. State Management with useState<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The Login component relies on useState to manage two pieces of state:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>isSignInForm: A boolean that determines whether the form is in &#8220;Sign In&#8221; or &#8220;Sign Up&#8221; mode.<\/li>\n\n\n\n<li>errorMessage: A string or null that holds any validation error messages.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">      const [isSignInForm, setIsSignInForm] = useState(true)\n      const [errorMessage, setErrorMessage] = useState(null)\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sign In\/Sign Up Toggle:<\/strong> This state toggles between sign-in and sign-up forms based on user action.<\/li>\n\n\n\n<li><strong>Error Handling:<\/strong> The errorMessage state captures and displays validation errors, improving the user experience by providing immediate feedback.<\/li>\n<\/ul>\n\n\n\n<h1 class=\"wp-block-heading\">&nbsp;<\/h1>\n\n\n\n<h1 class=\"wp-block-heading\">3. Refs for DOM Manipulation with useRef<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">useRef is used to create references to the input elements<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const email = useRef(null)\nconst password = useRef(null)\nconst firstName = useRef(null)\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Purpose of Refs:<\/strong> Refs allow direct access to the DOM elements. In this case, they help retrieve the values entered by the user without using controlled components (i.e., without the need to sync the input value with the component&#8217;s state).<\/li>\n\n\n\n<li><strong>Why use Refs here?<\/strong> By using refs, the component can quickly access input values, making it easy to validate or manipulate these values as needed.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">4. Form Handling and Validation<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The handleButtonClick function handles the form submission logic:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> const handleButtonClick = () =&gt; {\n setErrorMessage(checkValidate(email.current.value, password.current.value))\n }\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Validation:<\/strong> The checkValidate function (imported from ..\/utils\/validate) checks the validity of the email and password inputs. If validation fails, an error message is set, which will be displayed to the user.<\/li>\n\n\n\n<li><strong>Immediate Feedback:<\/strong> The validation logic ensures that users receive instant feedback if their input doesn&#8217;t meet the required criteria, enhancing the overall user experience.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">5. Input Components with Prop Forwarding with <strong><u>forwardRef()<\/u><\/strong> Hook<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The InputText component is a reusable input field built using forwardRef<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">import React, { forwardRef } from \"react\";\nconst InputText = forwardRef((props, ref) =&gt; { \nconsole.log(\"myProps\", props)\n return &lt;input  type=\"text\" ref={ref} placeholder={props.placeholder} {...props} \/&gt;\n})\nexport default InputText\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><u>forwardRef:<\/u><\/strong> This React method allows a component to forward its ref to a child component. This is crucial when you need to access the DOM element of a component but still want to keep the component reusable and flexible.<\/li>\n\n\n\n<li><strong><u>props and &#8230;props:<\/u><\/strong> The props object holds all properties passed to the InputText component. Using {&#8230;props} spreads these properties onto the input element, allowing it to inherit attributes like placeholder, onChange, etc.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">6. Form Toggle Functionality<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The toggleSignInForm function toggles between the sign-in and sign-up forms:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\"> const toggleSignInForm = () =&gt; { \n setIsSignInForm(!isSignInForm)\n  }\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Dynamic Form Rendering:<\/strong> Based on the value of isSignInForm, the form dynamically renders either a sign-in or a sign-up form. This approach reduces redundancy by reusing the same form structure for both purposes.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">7. Validation Logic<\/h1>\n\n\n\n<p class=\"wp-block-paragraph\">The checkValidate function ensures that user inputs are valid:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">export const checkValidate = (email, password) =&gt; { \nconst isEmailValid = \/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$\/.test(email)\nconst isPasswordValid = \/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&amp;])[A-Za-zd@$!%*?&amp;]8,}$\/.test(password)\n\n if (!isEmailValid) return \"Email ID is not valid\"\n if (!isPasswordValid) return \"Password is not valid\";\n\nreturn null\n }\n\n<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">For Code<\/p>\n\n\n\n<figure class=\"wp-block-embed\"><div class=\"wp-block-embed__wrapper\">\nhttps:\/\/github.com\/rasvpz\/netflixgpt\/tree\/validationWithReusbleComponent_useRef_forwardRef_Hooks\n<\/div><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This React login component serves as a solid foundation for building authentication interfaces in modern web applications. It demonstrates how to handle to create reusable UI elements, useState, useRef, controlled components, prop forwarding, forwardRef and manage form inputs, perform validation and use component composition to create reusable UI elements. By understanding and implementing these concepts,<\/p>\n","protected":false},"author":45,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[265,339,172,263,170],"tags":[226,224],"class_list":["post-4934","post","type-post","status-publish","format-standard","category-front-end-development","category-frontend","category-javascript","category-javascript-frameworks","category-reactjs","tag-frontend","tag-react"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/4934","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/users\/45"}],"replies":[{"embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/comments?post=4934"}],"version-history":[{"count":1,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/4934\/revisions"}],"predecessor-version":[{"id":4947,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/posts\/4934\/revisions\/4947"}],"wp:attachment":[{"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/media?parent=4934"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/categories?post=4934"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/namastedev.com\/blog\/wp-json\/wp\/v2\/tags?post=4934"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}