React tutorial using react portal and refs in typescript | CrewCode Solutions

React tutorial using react portal and refs in typescript

banner
banner
banner

React tutorial using react portal and refs in typescript

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 typescript project or you can skip this step if you wanted to use react portal and refs in to your existing project

npx create-react-app my-app --template typescript

Step 2: Using React portal in your react typescript project

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

This React portal component exists outside the DOM hierarchy of the parent component

Go to your /public/index.html file and there define a div with id other than root to render your portal

For example: i have defined another div with id as notification-root

<body class="bg-light">
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="notification-root"></div>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>

Step 3: Render your html element inside this newly created div that is notification-root using portal

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

For example i wanted to render a notification bar on top of my application layout that is top of my header

import ReactDOM from "react-dom";

const Notification = () => {
  return (
    <div className="alert alert-success" role="alert">
      A simple success alert—check it out!
    </div>
  );
};

const Login: React.FC<{}> = (props: any) => {
  const value = useContext(AuthContext);
  const navigate = useNavigate();
  const emailInputRef = useRef();
  return (
    <div>
      {ReactDOM.createPortal(
        <Notification />,
        document.getElementById("notification-root") as HTMLElement
      )}
      <LoginForm
        ref={emailInputRef}
        navigate={navigate}
        login={props.login}
        context={value}
      />
    </div>
  );
};

This will look something like this

portal

Step 4: Using refs in react typescript project

Refs provide a way to access DOM nodes or React elements created in the render method.

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

import React,{useRef} from "react";
import ReactDOM from "react-dom";

const Notification = () => {
  return (
    <div className="alert alert-success" role="alert">
      A simple success alert—check it out!
    </div>
  );
};

const LoginForm = (props:any) => {
    const getRefValue=()=>{
         console.log(props.ref.current.value);
    }
    return(
       <React.Fragment>
          <div className="form-floating">
            <input
              type="email"
              className="form-control"
              name="email"
              id="floatingInput"
              placeholder="name@example.com"
              ref={props.ref}
            />
            <label htmlFor="floatingInput">Email address</label>
          </div>
          <div className="form-floating mt-3">
            <input
              type="password"
              className="form-control"
              name="password"
              id="floatingPassword"
              placeholder="Password"
            />
            <label htmlFor="floatingPassword">Password</label>
          </div>
          <button
            onClick={()=>{
                getRefValue()

            }}
            className="w-100 btn btn-lg btn-warning"
            type="button"
          >
            Sign in
          </button>
        </React.Fragment>
    )

}

const Login: React.FC<{}> = (props: any) => {
  const value = useContext(AuthContext);
  const navigate = useNavigate();
  const emailInputRef = useRef();
  return (
    <div>
      {ReactDOM.createPortal(
        <Notification />,
        document.getElementById("notification-root") as HTMLElement
      )}
      <LoginForm
        ref={emailInputRef}
        navigate={navigate}
        login={props.login}
        context={value}
      />
    </div>
  );
};