2

I need to access my ref with a string variable that passed from props and contains the ref name that I want to get. something like this:

function MyComponent(props) {

    const myFirstRef = useRef();
    const mySecondRef = useRef();
    const myThirdRef = useRef();

    function handleClick() {
        const targetRef = props.targetRef;

        // The `targetRef` is a string that contains
        // the name of the one of the above refs!
        // I need to get my ref by string
        // ...
    }

    return (
        <div ref={myFirstRef}>
            <div ref={mySecondRef}>
                <div ref={myThirdRef}>
                    <button onClick={handleClick}>Find Ref and Do Something</button>
                </div>
            </div>
        </div>
    )

}

The targetRef is a string that contains the name of the above refs!

In class components there is this.refs and I could do what I want easily.

1
  • You can save your refs into a single object with different keys as it's name. Then you can access your ref with the object notation Commented Nov 22, 2019 at 10:05

1 Answer 1

2

You may want to use a dictionary as object for mapping given key targetRef to a specific reference:

const ref = useRef({ first: undefined, second: undefined, third: undefined });
ref.current[targetRef];
import React, { useRef } from 'react';
import ReactDOM from 'react-dom';

const RefContainer = ({ targetRef }) => {
  const ref = useRef({ first: undefined, second: undefined, third: undefined });

  const handleClick = () => {
    const coolRef = ref.current[targetRef];
    console.log(coolRef);
  };

  return (
    <div ref={node => (ref.current.first = node)}>
      <div ref={node => (ref.current.second = node)}>
        <div ref={node => (ref.current.third = node)}>
          <button onClick={handleClick}>Find Ref and Do Something</button>
        </div>
      </div>
    </div>
  );
};

const App = () => {
  return <RefContainer targetRef="third" />;
};

ReactDOM.render(<App />, document.getElementById('root'));

Edit react-antd-styled-template

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.