Skip to main content

Command Palette

Search for a command to run...

Refs in a Custom Component!

Published
1 min readView as Markdown
Refs in a Custom Component!

Note: Since Input Line 5 is a custom Component, the ref prop doesn't work, at least not out of the box. So how can we make refs work on custom Components?

All we have to do is to go to the Component where we wanna receive refs. In this case, that's the Input Component in the UI folder and then make sure we import React from react and wrap our Component function with React.forwardRef. So that Component function is now our argument to forwardRef. Then we get the ref which can now be set through the ref prop on our Component.

import React, { useRef, useState } from 'react'

function MealItemForm() {
    const amountInputRef = useRef();

    return (
 <form >
            <Input ref={amountInputRef}/> //Here Line 5
            <button>+ Add</button>
        </form>

    )
}

export default MealItemForm

More from this blog

Omar's blog

135 posts