Languages

How to use ref property in React component?

8 points
Asked by:
Anisha-Kidd
682

Why ref property doesn't work for my component in React?

1 answer
4 points
Answered by:
Anisha-Kidd
682

ref property is speacial property that can be passed only with forwardRef() function.

Example code:

import React, { forwardRef, useRef } from 'react';

const MyForm = forwardRef((props, ref) => {
    // some code here ...
    return (
        <form ref={ref}>
            {/* some JSX here ... */}
        </form>
    );
);

const App = () => {
    const formRef = useRef();
    return (
        <div>
          <MyForm ref={formRef} />
        </div>
    );
};

Where:

  • props constains all Myform component properities except ref property,
  • ref contains reference forwarded from outside.

 

See also

  1. React - how to forward reference to component

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join