SlideShare a Scribd company logo
1 of 4
Download to read offline
React with Ref
In this article, We will discuss the manipulation of DOM elements with
Ref directly with React.
React Framework builds your components and abstracts your code away
from manipulation within the DOM but still leaves the door open for
developers to access it. Reason are few cases where it might be
necessary. That's why React provides an escape hatch know as refs.
Refs are a function that use to access the DOM from components. You
only need to attach a ref to the element in your application to provide
access to it from anywhere within your component without making use
of props and all.
We can also use Refs to direct access to React elements and use
callbacks with them.
We should only use refs when the required interaction cannot be
achieved using state and props.
Use Refs
We can use refs to do anything that needs to be manipulated in the
DOM. Some good cases like focus, test selection, media playback,
triggering mandatory animations, or integration with the third-party
DOM library.
Note: We should avoid using refs because it removes the purpose of
using React. For example, If you want to show and hide a popup
component. We should use a boolean prop for it instead of manipulating
dom.
Creating Refs
We can use React.createRef()method to create Refs, and then we
can attach to a Dom element via the ref attribute after that, we can
access and modify that element through the ref.
class App extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef} />;
}
}
In above code, We created this.myRef in the constructor by calling
React.createRef() method.
Then in the render method , we attached the returned value to ref of
the div element, a reference to the node becomes accessible at the
current attribute of the ref.
We should not use ref attribute on function components because they
do not have instances.
React will assign the current property with Dom element when
component mount and assign null to it when component unmount.
ref updates happen before componentDidMount or
componentDidUpdate methods.
We can pass refs as props to the component. Example:
function MyCustomTextInput ({ myInputRef }) {
return <input ref={myInputRef} />;
}
class App extends React.Component {
constructor(props) {
super(props);
this.myInputRef = React.createRef();
}
componentDidMount() {
this.myInputRef.current.focus();
}
render() {
return <MyCustomTextInput inputRef={this.myInputRef} />;
}
}
In above code, App passed its ref as props to MyCustomTextInput
component.
You can read more in detail about call back ref in this tutorial about
React with Ref.

More Related Content

What's hot

Get rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directivesGet rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directivesMarios Fakiolas
 
Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Marios Fakiolas
 
What is Angular version 4?
What is Angular version 4?What is Angular version 4?
What is Angular version 4?Troy Miles
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?BOSC Tech Labs
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScriptAhmed El-Kady
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Knoldus Inc.
 
Developing a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2IDeveloping a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2INader Debbabi
 
Powershell of component object model COM Hijacking
Powershell of component object model COM Hijacking Powershell of component object model COM Hijacking
Powershell of component object model COM Hijacking harr0ey
 
Understand components in Angular 2
Understand components in Angular 2Understand components in Angular 2
Understand components in Angular 2codeandyou forums
 
Dive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceDive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceOleksii Prohonnyi
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript Rohit Bishnoi
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React NativeFITC
 
Beyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreBeyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreAri Lerner
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting StartedTracy Lee
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersPaweł Żurowski
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionDive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionOleksii Prohonnyi
 

What's hot (20)

Angular 2 - An Introduction
Angular 2 - An IntroductionAngular 2 - An Introduction
Angular 2 - An Introduction
 
Get rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directivesGet rid of controllers in angular 1.5.x start using component directives
Get rid of controllers in angular 1.5.x start using component directives
 
Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...Web components are the future of the web - Take advantage of new web technolo...
Web components are the future of the web - Take advantage of new web technolo...
 
What is Angular version 4?
What is Angular version 4?What is Angular version 4?
What is Angular version 4?
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?
 
Angular 4 - quick view
Angular 4 - quick viewAngular 4 - quick view
Angular 4 - quick view
 
Angular 5
Angular 5Angular 5
Angular 5
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScript
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
Developing a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2IDeveloping a Demo Application with Angular 4 - J2I
Developing a Demo Application with Angular 4 - J2I
 
Powershell of component object model COM Hijacking
Powershell of component object model COM Hijacking Powershell of component object model COM Hijacking
Powershell of component object model COM Hijacking
 
Understand components in Angular 2
Understand components in Angular 2Understand components in Angular 2
Understand components in Angular 2
 
Dive into Angular, part 3: Performance
Dive into Angular, part 3: PerformanceDive into Angular, part 3: Performance
Dive into Angular, part 3: Performance
 
Angular2 with TypeScript
Angular2 with TypeScript Angular2 with TypeScript
Angular2 with TypeScript
 
Intro To React Native
Intro To React NativeIntro To React Native
Intro To React Native
 
Beyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and moreBeyond AngularJS: Best practices and more
Beyond AngularJS: Best practices and more
 
React Native - Getting Started
React Native - Getting StartedReact Native - Getting Started
React Native - Getting Started
 
Quick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developersQuick introduction to Angular 4 for AngularJS 1.5 developers
Quick introduction to Angular 4 for AngularJS 1.5 developers
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: IntroductionDive into Angular, part 1: Introduction
Dive into Angular, part 1: Introduction
 
An Overview of Angular 4
An Overview of Angular 4 An Overview of Angular 4
An Overview of Angular 4
 

Similar to React with Ref

Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJSLinkMe Srl
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfBOSC Tech Labs
 
A React Journey
A React JourneyA React Journey
A React JourneyLinkMe Srl
 
Techpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdfTechpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdfTechpaathshala
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core ConceptsDivyang Bhambhani
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)Chiew Carol
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react jsBOSC Tech Labs
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !Ritesh Kumar
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)tuanpa206
 

Similar to React with Ref (20)

Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
React
ReactReact
React
 
Corso su ReactJS
Corso su ReactJSCorso su ReactJS
Corso su ReactJS
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdf
 
A React Journey
A React JourneyA React Journey
A React Journey
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
 
Techpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdfTechpaathshala ReactJS .pdf
Techpaathshala ReactJS .pdf
 
React patterns
React patternsReact patterns
React patterns
 
Copy of React_JS_Notes.pdf
Copy of React_JS_Notes.pdfCopy of React_JS_Notes.pdf
Copy of React_JS_Notes.pdf
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)React Native +Redux + ES6 (Updated)
React Native +Redux + ES6 (Updated)
 
reatppt.pptx
reatppt.pptxreatppt.pptx
reatppt.pptx
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
 
Welcome to React & Flux !
Welcome to React & Flux !Welcome to React & Flux !
Welcome to React & Flux !
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)
 
React a11y-csun
React a11y-csunReact a11y-csun
React a11y-csun
 
React js
React jsReact js
React js
 
React DOM/Virtual DOM
React DOM/Virtual DOMReact DOM/Virtual DOM
React DOM/Virtual DOM
 

More from Jack Forbes

Authentication and Authorization Defined_ What's the Difference_.pdf
Authentication and Authorization Defined_ What's the Difference_.pdfAuthentication and Authorization Defined_ What's the Difference_.pdf
Authentication and Authorization Defined_ What's the Difference_.pdfJack Forbes
 
Digital identity management for the cmo, ciso, and cio
Digital identity management for the cmo, ciso, and cioDigital identity management for the cmo, ciso, and cio
Digital identity management for the cmo, ciso, and cioJack Forbes
 
Step up authentication
Step up authenticationStep up authentication
Step up authenticationJack Forbes
 
Why do consumers prefer social login
Why do consumers prefer social loginWhy do consumers prefer social login
Why do consumers prefer social loginJack Forbes
 
How secure is two factor authentication (2 fa)
How secure is two factor authentication (2 fa)How secure is two factor authentication (2 fa)
How secure is two factor authentication (2 fa)Jack Forbes
 
Future of bring your own identity
Future of bring your own identityFuture of bring your own identity
Future of bring your own identityJack Forbes
 
Cms api integrations list-LoginRadius
Cms api integrations list-LoginRadiusCms api integrations list-LoginRadius
Cms api integrations list-LoginRadiusJack Forbes
 
Buyer’s guide to multi factor authentication
Buyer’s guide to multi factor authenticationBuyer’s guide to multi factor authentication
Buyer’s guide to multi factor authenticationJack Forbes
 
8 effective communication strategies for internal alignment and growth in 2021
8 effective communication strategies for internal alignment and growth in 20218 effective communication strategies for internal alignment and growth in 2021
8 effective communication strategies for internal alignment and growth in 2021Jack Forbes
 
Adaptive risk based authentication
Adaptive risk based authenticationAdaptive risk based authentication
Adaptive risk based authenticationJack Forbes
 
Social login-infographic
Social login-infographicSocial login-infographic
Social login-infographicJack Forbes
 
Login radius identity brokering infographic
Login radius identity brokering infographicLogin radius identity brokering infographic
Login radius identity brokering infographicJack Forbes
 
Web and Mobile SSO
Web and Mobile SSOWeb and Mobile SSO
Web and Mobile SSOJack Forbes
 
Loginradius phone authentication
Loginradius phone authenticationLoginradius phone authentication
Loginradius phone authenticationJack Forbes
 
Identity and Access Management (IAM)
Identity and Access Management (IAM)Identity and Access Management (IAM)
Identity and Access Management (IAM)Jack Forbes
 
Social Login Explained
Social Login ExplainedSocial Login Explained
Social Login ExplainedJack Forbes
 
A Guide to Multi Factor Authentication
A Guide to Multi Factor AuthenticationA Guide to Multi Factor Authentication
A Guide to Multi Factor AuthenticationJack Forbes
 
Ciam for devops
Ciam for devops Ciam for devops
Ciam for devops Jack Forbes
 
Defining the omnichannel customer experience
Defining the omnichannel customer experienceDefining the omnichannel customer experience
Defining the omnichannel customer experienceJack Forbes
 

More from Jack Forbes (20)

Authentication and Authorization Defined_ What's the Difference_.pdf
Authentication and Authorization Defined_ What's the Difference_.pdfAuthentication and Authorization Defined_ What's the Difference_.pdf
Authentication and Authorization Defined_ What's the Difference_.pdf
 
Digital identity management for the cmo, ciso, and cio
Digital identity management for the cmo, ciso, and cioDigital identity management for the cmo, ciso, and cio
Digital identity management for the cmo, ciso, and cio
 
Step up authentication
Step up authenticationStep up authentication
Step up authentication
 
Why do consumers prefer social login
Why do consumers prefer social loginWhy do consumers prefer social login
Why do consumers prefer social login
 
How secure is two factor authentication (2 fa)
How secure is two factor authentication (2 fa)How secure is two factor authentication (2 fa)
How secure is two factor authentication (2 fa)
 
Future of bring your own identity
Future of bring your own identityFuture of bring your own identity
Future of bring your own identity
 
Cms api integrations list-LoginRadius
Cms api integrations list-LoginRadiusCms api integrations list-LoginRadius
Cms api integrations list-LoginRadius
 
Buyer’s guide to multi factor authentication
Buyer’s guide to multi factor authenticationBuyer’s guide to multi factor authentication
Buyer’s guide to multi factor authentication
 
8 effective communication strategies for internal alignment and growth in 2021
8 effective communication strategies for internal alignment and growth in 20218 effective communication strategies for internal alignment and growth in 2021
8 effective communication strategies for internal alignment and growth in 2021
 
Adaptive risk based authentication
Adaptive risk based authenticationAdaptive risk based authentication
Adaptive risk based authentication
 
Social login-infographic
Social login-infographicSocial login-infographic
Social login-infographic
 
Login radius identity brokering infographic
Login radius identity brokering infographicLogin radius identity brokering infographic
Login radius identity brokering infographic
 
Web and Mobile SSO
Web and Mobile SSOWeb and Mobile SSO
Web and Mobile SSO
 
Loginradius phone authentication
Loginradius phone authenticationLoginradius phone authentication
Loginradius phone authentication
 
Identity and Access Management (IAM)
Identity and Access Management (IAM)Identity and Access Management (IAM)
Identity and Access Management (IAM)
 
Social Login Explained
Social Login ExplainedSocial Login Explained
Social Login Explained
 
A Guide to Multi Factor Authentication
A Guide to Multi Factor AuthenticationA Guide to Multi Factor Authentication
A Guide to Multi Factor Authentication
 
Guide to MFA
Guide to MFAGuide to MFA
Guide to MFA
 
Ciam for devops
Ciam for devops Ciam for devops
Ciam for devops
 
Defining the omnichannel customer experience
Defining the omnichannel customer experienceDefining the omnichannel customer experience
Defining the omnichannel customer experience
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

React with Ref

  • 1. React with Ref In this article, We will discuss the manipulation of DOM elements with Ref directly with React. React Framework builds your components and abstracts your code away from manipulation within the DOM but still leaves the door open for developers to access it. Reason are few cases where it might be necessary. That's why React provides an escape hatch know as refs.
  • 2. Refs are a function that use to access the DOM from components. You only need to attach a ref to the element in your application to provide access to it from anywhere within your component without making use of props and all. We can also use Refs to direct access to React elements and use callbacks with them. We should only use refs when the required interaction cannot be achieved using state and props. Use Refs We can use refs to do anything that needs to be manipulated in the DOM. Some good cases like focus, test selection, media playback, triggering mandatory animations, or integration with the third-party DOM library. Note: We should avoid using refs because it removes the purpose of using React. For example, If you want to show and hide a popup component. We should use a boolean prop for it instead of manipulating dom. Creating Refs
  • 3. We can use React.createRef()method to create Refs, and then we can attach to a Dom element via the ref attribute after that, we can access and modify that element through the ref. class App extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } render() { return <div ref={this.myRef} />; } } In above code, We created this.myRef in the constructor by calling React.createRef() method. Then in the render method , we attached the returned value to ref of the div element, a reference to the node becomes accessible at the current attribute of the ref. We should not use ref attribute on function components because they do not have instances. React will assign the current property with Dom element when component mount and assign null to it when component unmount. ref updates happen before componentDidMount or componentDidUpdate methods.
  • 4. We can pass refs as props to the component. Example: function MyCustomTextInput ({ myInputRef }) { return <input ref={myInputRef} />; } class App extends React.Component { constructor(props) { super(props); this.myInputRef = React.createRef(); } componentDidMount() { this.myInputRef.current.focus(); } render() { return <MyCustomTextInput inputRef={this.myInputRef} />; } } In above code, App passed its ref as props to MyCustomTextInput component. You can read more in detail about call back ref in this tutorial about React with Ref.