React Mastery / React Core Concepts

Refs with Class Components

🧠 What are Refs in Class Components?

In class components, Refs are used to directly access a DOM element or a child component — just like in functional components, but the syntax is different.


🧩 Steps to Use Refs in Class Components

1️⃣ Create the Ref in the constructor

this.inputRef = React.createRef();

2️⃣ Attach the Ref to a DOM element

<input type="text" ref={this.inputRef} />

3️⃣ Use the Ref (e.g., to focus the input)

this.inputRef.current.focus();

📦 Full Example


✅ Explanation of the Class Component with Refs

  • class MyClassComponent extends Component

    → Creates a class-based React component

  • constructor(props)

    → Initializes the component and prepares refs

  • super(props)

    → Passes props to the parent Component class

  • this.inputRef = React.createRef()

    → Creates a ref to directly access the input element

  • ref={this.inputRef}

    → Attaches the ref to the <input> element

  • handleClick = () => { ... }

    → Arrow function keeps this automatically bound

  • this.inputRef.current

    → Points to the actual input DOM element

  • .focus()

    → Moves the cursor into the input box

  • <button onClick={this.handleClick}>

    → Clicking the button focuses the input field


🔁 Summary Table

Step

Code

Create Ref

this.myRef = React.createRef();

Attach Ref

<input ref={this.myRef} />

Use Ref

this.myRef.current.focus();