Skip to main content

Utilizing Ref Attribute for Referring HTML or React Elements

For accessing the DOM node of an HTML element or referring a React element, we can utilize the ref attribute. In React, we can utilize React.crateRef() function or React.useRef() hook for generating an object that has access to the referred DOM node. Several cases may be faced while we are developing React application.


1) Referring HTML Element.

class RefHtml extends React.Component {
  constructor(props){
    super(props);
    this.textInput = React.createRef();
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.textInput} />
        <button onClick={()=>{this.textInput.current.focus();}}>Focus</button>
      </div>
    );
  }
}

2) Referring React Element (Class Component).

class ReferredElement extends React.Component {
  constructor(props){
    super(props);
    this.state = {status: "inactive"};
  }

  setActiveState() {
    this.setState({status: "active"});
  }

  render() {
    return <div>Status: {this.state.status}</div>
  }
}

class RefReact extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  render() {
    return (
      <div>
        <ReferredElement ref={this.childRef} />
        <button onClick={()=>{this.childRef.current.setActiveState()}}>Run setActiveState</button>
      </div>
    )
  }
}

3) Referring An Element In A Function Component. In this case, React.useRef() hook is used.

function RefFunc() {
  const textInputRef = React.useRef(null);

  function focusToInput() {
    if (textInput) {
      textInputRef.current.focus();
    }
  }

  return (<div>
    <input type="text" ref={textInputRef} />
    <button onClick={focusToInput}>Focus</button>
  </div>);
}

4) Referring Using Callback Function.

class RefCallback extends React.Component {
  constructor(props){
    super(props);
    this.textInputRef = null;
  }

  focusToInput() {
    if (this.textInputRef) {
      this.textInputRef.focus();
    }
  }

  render() {
    return (
      <div>
        <input ref={(elmnt)=>{this.textInputRef = elmnt;}} />
        <button onClick={()=>{this.focusToInput();}}>Focus</button>
      </div>
    )
  }
}

5) Referring An Element In Child Component Using Callback Function.

function RefCallbackChild(props) {
  return (
    <input type="text" ref={props.callbackRef} />
  )
}

class RefCallbackParent extends React.Component {
  constructor(props) {
    super(props);
    this.textInputRef = null;
  }

  render() {
    return (
      <div>
        <RefCallbackChild callbackRef={(elmnt) => {this.textInputRef = elmnt}} />
        <button onClick={()=>{this.textInputRef.focus();}}>Focus</button>
      </div>
    );
  }
}

6) Forwarding Reference Into A Function Component Using ForwardRef. The React.forwardRef() function can be used to forward the ref value into a function component.

function CustomInputElement(props, ref) {
  return (
    <div>
      <input ref={ref} />
      <button>{props.children}</button>
    </div>
  )
}

const CustomInput = React.forwardRef(CustomInputElement);

class CustomInputParent extends React.Component {
  constructor(props) {
    super(props);
    this.customInputRef = React.createRef();
  }

  render() {
    return (
      <div>
        <button onClick={()=>{this.customInputRef.current.focus();}}>Focus</button>
        <CustomInput ref={this.customInputRef}>Custom Input Button</CustomInput>
      </div>
    );
  }
}

7) Forwarding Reference Into An Element Created By Higher-Order-Component Function. If we create an element by HOC function, reference will be consumed by wrapper component, not by the component which is wrapped. Take a look this following HOC function.

function hoc(WrappedComponent) {
  class Wrapper extends React.Component {
    render() {
      return (
        <WrappedComponent {...this.props} />
      );
    }
  }

  return Wrapper;
}

As we see, the result of the HOC function is another component which is the Wrapper class. If we pass a reference, it cannot be directly accessed by the WrappedComponent class. The React.forwardRef() function can be used and modification of HOC function is required.

function hoc(WrappedComponent) {
  class Wrapper extends React.Component {
    render() {
      const {forwardedRef, ...rest} = this.props;

      return (
        <WrappedComponent ref={forwardedRef} {...rest} />
      );
    }
  }

  function forwardedElement(props, ref) {
    return (
      <Wrapper {...props} forwardedRef={ref} />
    );
  }

  return React.forwardRef(forwardedElement);
}

class WrappedInputElement extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = createRef();
  }

  focusToInput() {
    this.inputRef.current.focus();
  }

  render() {
    return (
      <input type="text" ref={this.inputRef} />
    )
  }
}

const WrappedInput = hoc(WrappedInputElement);

class WrappedInputParent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return (
      <div>
        <WrappedInput ref={this.inputRef} />
        <button onClick={()=>{this.inputRef.current.focusToInput();}}>Focus</button>
      </div>
    )
  }
}

Comments

Popular posts from this blog

Deploying a Web Server on UpCloud using Terraform Modules

In my earlier post , I shared an example of deploying UpCloud infrastructure using Terraform from scratch. In this post, I want to share how to deploy the infrastructure using available Terraform modules to speed up the set-up process, especially for common use cases like preparing a web server. For instance, our need is to deploy a website with some conditions as follows. The website can be accessed through HTTPS. If the request is HTTP, it will be redirected to HTTPS. There are 2 domains, web1.yourdomain.com and web2.yourdomain.com . But, users should be redirected to "web2" if they are visiting "web1". There are 4 main modules that we need to set up the environment. Private network. It allows the load balancer to connect with the server and pass the traffic. Server. It is used to host the website. Load balancer. It includes backend and frontend configuration. Dynamic certificate. It is requ...

Increase of Malicious Activities and Implementation of reCaptcha

In recent time, I've seen the increase of malicious activities such as login attempts or phishing emails to some accounts I manage. Let me list some of them and the actions taken. SSH Access Attempts This happened on a server that host a Gitlab server. Because of this case, I started to limit the incoming traffic to the server using internal and cloud firewall provided by the cloud provider. I limit the exposed ports, connected network interfaces, and allowed protocols. Phishing Attempts This typically happened through email and messaging platform such as Whatsapp and Facebook Page messaging. The malicious actors tried to share a suspicious link lured as invoice, support ticket, or something else. Malicious links shared Spammy Bot The actors leverage one of public endpoint on my website to send emails. Actually, the emails won't be forwarded anywhere except to my own email so this just full my inbox. This bot is quite active, but I'm still not sure what...

How To Discover Exposed Digital Assets for Free Using Noxtara

If you have a website or public-facing digital assets, you might wonder whether they’re secure and what potential entry points could be at risk. A great first step is to list all the digital assets connected to your main domain. One free tool that can help with this is called Noxtara. It offers a variety of security tools in one integrated dashboard, including a feature for discovering public-facing assets. Creating a free account is simple—just head over to the registration page . If you’ve got a company email that matches the domain you want to scan, it’s best to use that since it makes adding the domain to the Noxtara platform much easier. No worries if you don’t have a company email, though; you can still sign up without a problem. Just keep in mind that when you want to add your company’s domain for scanning, you’ll need to go through a quick DNS record check. Registration Once you’ve registered, you can set up a team and add your domain in the team settings. If the domai...

What's Good About Strapi, a Headless CMS

Recently, I've been revisiting Strapi as a solution for building backend systems. I still think this headless CMS can be quite useful in certain cases, especially for faster prototyping or creating common websites like company profiles or e-commerce platforms . It might even have the potential to handle more complex systems. With the release of version 5, I'm curious to know what updates it brings. Strapi has launched a new documentation page, and it already feels like an improvement in navigation and content structure compared to the previous version. That said, there's still room for improvement, particularly when it comes to use cases and best practices for working with Strapi. In my opinion, Strapi stands out with some compelling features that could catch developers' attention. I believe three key aspects of Strapi offer notable advantages. First, the content-type builder feature lets us design the data structure of an entity or database model , including ...

Manage Kubernetes Cluster using Rancher

Recently, I sought a simpler method to deploy and maintain Kubernetes clusters across various cloud providers. The goal was to use it for development purposes with the ability to manage the infrastructure and costs effortlessly. After exploring several options, I decided to experiment with Rancher. Rancher offers a comprehensive software stack for teams implementing container technology. It tackles both the operational and security hurdles associated with managing numerous Kubernetes clusters. Additionally, it equips DevOps teams with integrated tools essential for managing containerized workloads. Rancher also offers an open-source version, allowing free deployment within one's infrastructure. The Rancher platform can be deployed either as a Docker container or within a Kubernetes cluster utilizing the K3s engine. We can read the documentation on how to install Rancher on K3s using Helm . Rancher itself enables the creation and provisioning of Kubernetes clusters and ...

How To Verify Phone Number for Free Using WhatsApp

If you have a product or business that maintains user information like phone numbers, verifying the validity or ownership of the phone number could become important, as the phone number can be used as an authentication method or targeted marketing channel. The typical phone verification procedure is by generating a code or OTP in our application, sending that OTP to the user's phone, and then the user should insert the OTP in our application for verification. The OTP can be sent to the users through services like SMS or WhatsApp that require a valid phone number. For internet-based communication, WhatsApp has become the de facto standard for sending the OTP. WhatsApp requires its users to have a valid phone number during account creation, and it already has a huge number of users, approximately 3 billion in 2025. Using that common procedure, WhatsApp will charge us for each OTP sent. The cost depends on the country of the target phone number. For Indonesia...