

{"id":113132,"date":"2023-05-23T09:00:58","date_gmt":"2023-05-23T03:30:58","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=113132"},"modified":"2023-05-23T14:38:25","modified_gmt":"2023-05-23T09:08:25","slug":"refs-in-react","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/refs-in-react\/","title":{"rendered":"Refs in React"},"content":{"rendered":"<p>Refs in React provide a way to access and manipulate the DOM elements or components directly. Refs are a powerful feature of React, allowing developers to interact with elements that are outside of the normal React data flow. In this article, we will go through everything you need to know about using refs in React.<\/p>\n<h3>What are refs in React?<\/h3>\n<p>Refs in React are a way to access and manipulate the DOM elements or components directly. Refs allow you to reference a specific element, like an input field or a button, and then interact with it directly in your code.<\/p>\n<h3>Ways to create refs in react<\/h3>\n<p>There are two ways to create refs in React:<\/p>\n<h4>1. Using the React.createRef() method to create a ref and assign it to an instance variable:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class ExampleComponent extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.myRef = React.createRef();\r\n  }\r\n  \r\n  render() {\r\n    return &lt;div ref={this.myRef}&gt;Hello World&lt;\/div&gt;;\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">Hello World<\/div>\n<h4>2. Using the ref attribute in JSX to create a callback function that takes a reference to the DOM element or component:<\/h4>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class ExampleComponent extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.myRef = null;\r\n    this.setRef = element =&gt; {\r\n      this.myRef = element;\r\n    };\r\n  }\r\n  \r\n  render() {\r\n    return &lt;div ref={this.setRef}&gt;Hello from DataFlair&lt;\/div&gt;;\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">Hello from DataFlair<\/div>\n<h3>Uses of refs in React<\/h3>\n<p>There are several use cases for refs in React. Here are a few examples:<\/p>\n<h4>1. Accessing form data<\/h4>\n<p>Refs can be used to access the form data in a React application. For example, you can use a ref to get the value of an input field:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyForm extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.inputRef = React.createRef();\r\n  }\r\n\r\n  handleSubmit = (event) =&gt; {\r\n    event.preventDefault();\r\n    console.log(this.inputRef.current.value);\r\n  };\r\n\r\n  render() {\r\n    return (\r\n      &lt;form onSubmit={this.handleSubmit}&gt;\r\n        &lt;label&gt;\r\n          Name of DataFlair's reader  :\r\n          &lt;input type=\"text\" ref={this.inputRef} \/&gt;\r\n        &lt;\/label&gt;\r\n        &lt;button type=\"submit\"&gt;Submit&lt;\/button&gt;\r\n      &lt;\/form&gt;\r\n    );\r\n  }\r\n}\r\n\r\nReactDOM.render(&lt;MyForm \/&gt;, document.getElementById(\"root\"));\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113531\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.png\" alt=\"react refs\" width=\"655\" height=\"79\" \/><\/a><\/p>\n<h4>2. Animating elements<\/h4>\n<p>Refs can be used to animate elements in a React application. For example, you can use a ref to get the height of an element and then use that value to animate it:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyComponent extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.myRef = React.createRef();\r\n  }\r\n  \r\n  handleClick = () =&gt; {\r\n    const height = this.myRef.current.offsetHeight;\r\n    \/\/ animate the element using the height value\r\n  }\r\n  \r\n  render() {\r\n    return (\r\n      &lt;div ref={this.myRef} onClick={this.handleClick}&gt;\r\n        Hello World\r\n      &lt;\/div&gt;\r\n    );\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">Hello World<\/div>\n<h4>3. Integrating with third-party libraries<\/h4>\n<p>Refs can be used to integrate with third-party libraries in a React application. For example, you can use a ref to get a reference to a third-party library object and then interact with it directly:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyComponent extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.myRef = React.createRef();\r\n  }\r\n  \r\n  componentDidMount() {\r\n    const thirdPartyObject = new ThirdPartyLibrary(this.myRef.current);\r\n    \/\/ interact with the third-party object\r\n  }\r\n  \r\n  render() {\r\n    return &lt;div ref={this.myRef}&gt;Hell, from DataFlair&lt;\/div&gt;;\r\n  }\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<div class=\"code-output\">Hello, from DataFlair<\/div>\n<h3>Using Refs with Class Components<\/h3>\n<p>Refs can also be used with class components in React. Here\u2019s an example of using a ref with a class component:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import React, { Component } from 'react';\r\n\r\nclass MyComponent extends Component {\r\n  constructor(props) {\r\n    super(props);\r\n\r\n    this.myRef = React.createRef();\r\n  }\r\n\r\n  handleClick() {\r\n    this.myRef.current.focus();\r\n  }\r\n\r\n  render() {\r\n    return (\r\n      &lt;div&gt;\r\n        &lt;input type=\"text\" ref={this.myRef} \/&gt;\r\n        &lt;button onClick={() =&gt; this.handleClick()}&gt;Focus input&lt;\/button&gt;\r\n      &lt;\/div&gt;\r\n    );\r\n  }\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/class-components.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113532\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/class-components.png\" alt=\"class components\" width=\"442\" height=\"68\" \/><\/a><\/p>\n<p>In the above example, we create a ref in the component\u2019s constructor using React.createRef(), and then attach it to an input element using the ref attribute. We also define a handleClick method that calls focus() on the input element\u2019s ref.<\/p>\n<p>When the Focus input button is clicked, the handleClick method is called, which focuses the input element.<\/p>\n<h3>Using Refs with Functional Components<\/h3>\n<p>Refs can also be used with functional components in React. Here\u2019s an example of using a ref with a functional component using the useRef hook:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import React, { useRef } from 'react';\r\n\r\nfunction MyComponent() {\r\n  const myRef = useRef(null);\r\n\r\n  const handleClick = () =&gt; {\r\n    myRef.current.focus();\r\n  };\r\n\r\n  return (\r\n    &lt;div&gt;\r\n      &lt;input type=\"text\" ref={myRef} \/&gt;\r\n      &lt;button onClick={handleClick}&gt;Focus input&lt;\/button&gt;\r\n    &lt;\/div&gt;\r\n  );\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/functional-components.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113533\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/functional-components.png\" alt=\"functional components\" width=\"400\" height=\"106\" \/><\/a><\/p>\n<p>In this example, we use the useRef hook to create a ref and attach it to an input element using the ref attribute.<\/p>\n<h3>Limitations of Refs in React<\/h3>\n<p>While refs can be a useful tool in certain situations, there are also some limitations and potential drawbacks to be aware of when using them in React:<\/p>\n<p><strong>1. Refs can make code harder to understand and maintain:<\/strong><\/p>\n<p>When overused or used inappropriately, refs can make code more complex and harder to follow. This can lead to difficulties in debugging and maintaining the code over time.<\/p>\n<p><strong>2. Refs can create a tight coupling between components:<\/strong><\/p>\n<p>When a component is coupled to its child components through the use of refs, it can make it harder to reuse the component in different contexts.<\/p>\n<p><strong>3. Refs are not recommended for managing component state:<\/strong><\/p>\n<p>While it is possible to use refs to manage component state, this is not recommended as it can make the code more error-prone and harder to reason about. It is generally better to manage component state using React&#8217;s built-in state management tools.<\/p>\n<p><strong>4. Refs can be difficult to use with functional components:<\/strong><\/p>\n<p>While it is possible to use refs with functional components using the useRef hook<\/p>\n<p><strong>5. Refs can create performance issues:<\/strong><\/p>\n<p>Since refs can cause a component to be re-rendered even if its props have not changed, they can potentially create performance issues if used excessively or inappropriately.<\/p>\n<h3>When to use react refs?<\/h3>\n<p><strong>Accessing DOM elements:<\/strong> Refs can be used to get a reference to a DOM element, so that it can be manipulated directly. For example, if you need to focus an input field or scroll a container, you can use refs to access the DOM element and call its methods.<\/p>\n<p><strong>Animating elements:<\/strong> Refs can be used to animate elements, such as when building complex animations that require fine-grained control over the underlying DOM. For example, you can use a ref to access the DOM element and apply CSS transitions or animations to it.<\/p>\n<h3>When not to use refs in react?<\/h3>\n<p><strong>State management:<\/strong> Refs should not be used to manage state in a React component. State should be managed using useState or useReducer hooks, which provide a clear and predictable way to update the state of a component.<\/p>\n<p><strong>Conditional rendering<\/strong>: Refs should not be used to conditionally render components. Conditional rendering should be done using if statements or ternary operators, which provide a clear and concise way to render components based on a condition.<\/p>\n<h3>Conclusion<\/h3>\n<p>This was all about react refs, ways to create it, its limitations and uses.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Refs in React provide a way to access and manipulate the DOM elements or components directly. Refs are a powerful feature of React, allowing developers to interact with elements that are outside of the&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":113530,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27227],"tags":[27420],"class_list":["post-113132","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-tutorials","tag-refs-in-react"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Refs in React - DataFlair<\/title>\n<meta name=\"description\" content=\"Refs in React provide a way to access and manipulate the DOM elements or components directly. See ways to create it, its limitations &amp; uses.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/refs-in-react\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Refs in React - DataFlair\" \/>\n<meta property=\"og:description\" content=\"Refs in React provide a way to access and manipulate the DOM elements or components directly. See ways to create it, its limitations &amp; uses.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/refs-in-react\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-23T03:30:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-23T09:08:25+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"6 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Refs in React - DataFlair","description":"Refs in React provide a way to access and manipulate the DOM elements or components directly. See ways to create it, its limitations & uses.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/refs-in-react\/","og_locale":"en_US","og_type":"article","og_title":"Refs in React - DataFlair","og_description":"Refs in React provide a way to access and manipulate the DOM elements or components directly. See ways to create it, its limitations & uses.","og_url":"https:\/\/data-flair.training\/blogs\/refs-in-react\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-05-23T03:30:58+00:00","article_modified_time":"2023-05-23T09:08:25+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"6 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"Refs in React","datePublished":"2023-05-23T03:30:58+00:00","dateModified":"2023-05-23T09:08:25+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/"},"wordCount":838,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp","keywords":["Refs in React"],"articleSection":["React Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/refs-in-react\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/","url":"https:\/\/data-flair.training\/blogs\/refs-in-react\/","name":"Refs in React - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp","datePublished":"2023-05-23T03:30:58+00:00","dateModified":"2023-05-23T09:08:25+00:00","description":"Refs in React provide a way to access and manipulate the DOM elements or components directly. See ways to create it, its limitations & uses.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/refs-in-react\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-refs.webp","width":1200,"height":628,"caption":"react refs"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/refs-in-react\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"React Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/react-tutorials\/"},{"@type":"ListItem","position":3,"name":"Refs in React"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113132","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=113132"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113132\/revisions"}],"predecessor-version":[{"id":113534,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113132\/revisions\/113534"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/113530"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=113132"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=113132"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=113132"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}