{
    "componentChunkName": "component---src-templates-blog-post-js",
    "path": "/react-tutorial-using-react-portals-refs-typescript/",
    "result": {"data":{"site":{"siteMetadata":{"title":"CrewCode Solutions"}},"markdownRemark":{"id":"bc5ca7cf-a9a9-51bf-a020-f308b4061a7a","excerpt":"In this article i will explain you how you can use react portals and refs in your react typescript project Step 1: Create React typescript project Create react…","html":"<p>In this article i will explain you how you can use react portals and refs in your react typescript project</p>\n<h4>Step 1: Create React typescript project</h4>\n<p>Create react typescript project or you can skip this step if you wanted to use react portal and refs in to your existing project</p>\n<pre><code class=\"language-js\">npx create-react-app my-app --template typescript\n</code></pre>\n<h4>Step 2: Using React portal in your react typescript project</h4>\n<p>Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.</p>\n<p>This React portal component exists outside the DOM hierarchy of the parent component</p>\n<p>Go to your <strong><em>/public/index.html</em></strong> file and there define a div with id other than root to render your portal</p>\n<p>For example: i have defined another div with id as <strong><em>notification-root</em></strong></p>\n<pre><code class=\"language-js\">&#x3C;body class=\"bg-light\">\n    &#x3C;noscript>You need to enable JavaScript to run this app.&#x3C;/noscript>\n    &#x3C;div id=\"notification-root\">&#x3C;/div>\n    &#x3C;div id=\"root\">&#x3C;/div>\n    &#x3C;!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the &#x3C;body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  &#x3C;/body>\n</code></pre>\n<h4>Step 3: Render your html element inside this newly created div that is notification-root using portal</h4>\n<p>Go to your component where you wanted this custom html element to render inside your notification-root div and this piece of code for example i'm using Login.tsx</p>\n<p>For example i wanted to render a notification bar on top of my application layout that is top of my header</p>\n<pre><code class=\"language-js\">import ReactDOM from \"react-dom\";\n\nconst Notification = () => {\n  return (\n    &#x3C;div className=\"alert alert-success\" role=\"alert\">\n      A simple success alert—check it out!\n    &#x3C;/div>\n  );\n};\n\nconst Login: React.FC&#x3C;{}> = (props: any) => {\n  const value = useContext(AuthContext);\n  const navigate = useNavigate();\n  const emailInputRef = useRef();\n  return (\n    &#x3C;div>\n      {ReactDOM.createPortal(\n        &#x3C;Notification />,\n        document.getElementById(\"notification-root\") as HTMLElement\n      )}\n      &#x3C;LoginForm\n        ref={emailInputRef}\n        navigate={navigate}\n        login={props.login}\n        context={value}\n      />\n    &#x3C;/div>\n  );\n};\n</code></pre>\n<p>This will look something like this</p>\n<p><img src=\"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/React-tutorial-using-react-1.png\" alt=\"portal\"></p>\n<h4>Step 4: Using refs in react typescript project</h4>\n<p>Refs provide a way to access DOM nodes or React elements created in the render method.</p>\n<p>I will use same login form to demonstrate the refs for example you have email and password input and you want to access the email and password value on button click then you need to use refs like this</p>\n<pre><code class=\"language-js\">import React,{useRef} from \"react\";\nimport ReactDOM from \"react-dom\";\n\nconst Notification = () => {\n  return (\n    &#x3C;div className=\"alert alert-success\" role=\"alert\">\n      A simple success alert—check it out!\n    &#x3C;/div>\n  );\n};\n\nconst LoginForm = (props:any) => {\n    const getRefValue=()=>{\n         console.log(props.ref.current.value);\n    }\n    return(\n       &#x3C;React.Fragment>\n          &#x3C;div className=\"form-floating\">\n            &#x3C;input\n              type=\"email\"\n              className=\"form-control\"\n              name=\"email\"\n              id=\"floatingInput\"\n              placeholder=\"name@example.com\"\n              ref={props.ref}\n            />\n            &#x3C;label htmlFor=\"floatingInput\">Email address&#x3C;/label>\n          &#x3C;/div>\n          &#x3C;div className=\"form-floating mt-3\">\n            &#x3C;input\n              type=\"password\"\n              className=\"form-control\"\n              name=\"password\"\n              id=\"floatingPassword\"\n              placeholder=\"Password\"\n            />\n            &#x3C;label htmlFor=\"floatingPassword\">Password&#x3C;/label>\n          &#x3C;/div>\n          &#x3C;button\n            onClick={()=>{\n                getRefValue()\n\n            }}\n            className=\"w-100 btn btn-lg btn-warning\"\n            type=\"button\"\n          >\n            Sign in\n          &#x3C;/button>\n        &#x3C;/React.Fragment>\n    )\n\n}\n\nconst Login: React.FC&#x3C;{}> = (props: any) => {\n  const value = useContext(AuthContext);\n  const navigate = useNavigate();\n  const emailInputRef = useRef();\n  return (\n    &#x3C;div>\n      {ReactDOM.createPortal(\n        &#x3C;Notification />,\n        document.getElementById(\"notification-root\") as HTMLElement\n      )}\n      &#x3C;LoginForm\n        ref={emailInputRef}\n        navigate={navigate}\n        login={props.login}\n        context={value}\n      />\n    &#x3C;/div>\n  );\n};\n</code></pre>","fields":{"slug":"/react-tutorial-using-react-portals-refs-typescript/"},"frontmatter":{"title":"React tutorial using react portal and refs in typescript","date":"March 30, 2023","description":"In this article i will explain you to use react portal and refs in typescript","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/React.jpg"}},"previous":{"fields":{"slug":"/react-tutorial-using-hoc-in-react-typescript-project/"},"frontmatter":{"title":"React tutorial using high order component in react typescript project","date":"March 20, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/React.jpg"}},"next":{"fields":{"slug":"/react-tutorial-using-react-router6-typescript/"},"frontmatter":{"title":"React tutorial using react router v6 in react typescript with nested routes","date":"April 04, 2023","bannerimage":"https://crew-code-images.s3.us-east-1.amazonaws.com/blog_images/React.jpg"}}},"pageContext":{"id":"bc5ca7cf-a9a9-51bf-a020-f308b4061a7a","previousPostId":"3e3b2299-69e9-5128-9a84-a38cb7e1c60e","nextPostId":"72a4892b-edf3-5513-90ce-f24179cc276d"}},
    "staticQueryHashes": ["3860684146"]}