React JS Tutorial: `createRef`

beginner
23 min

React JS Tutorial: createRef

Welcome to our comprehensive guide on the createRef function in React JS! This tutorial is designed to help both beginners and intermediates understand this essential concept. Let's dive in! 🎯

Understanding createRef

createRef is a built-in hook in React that allows you to create a reference to a React element. This can be particularly useful when you need to access the DOM node or instance of a component. 📝

Why use createRef?

  1. Accessing DOM nodes: Sometimes, you might need to access the DOM node of a React element, for example, to implement third-party libraries that require direct DOM manipulation.

  2. Forwarding refs: If you want to create a reusable component that can accept a ref, you can use createRef. This will be covered in a future lesson.

Creating a Ref

Let's create a simple ref and see it in action.

jsx
import React, { createRef } from 'react'; function RefExample() { const myRef = createRef(); return ( <div> <h1 ref={myRef}>Hello, World!</h1> <button onClick={() => myRef.current.style.color = 'red'}>Change Color</button> </div> ); }

In the above example, we've created a ref named myRef using createRef(). We've then attached this ref to the h1 element using the ref attribute. The button click event changes the color of the h1 text to red by accessing the DOM node via the ref's current property.

Quiz Time 📝

Quick Quiz
Question 1 of 1

What does `createRef` do in React?

Stay tuned for our next lesson, where we'll explore how to use refs to focus on inputs and more! 🚀