0

I need to pass the refs from one component to a function passed in from another component as a prop, and I need to do it in typescript.

So the relevant code inside the child component is

class Login extends Component<IProps, IState>  {
    private emailRef = React.createRef<HTMLInputElement>();
    private passRef = React.createRef<HTMLInputElement>();

    constructor(props?) {
        super(props);
    }

    login = () => {
        const email = this.emailRef.current;
        const pass = this.passRef.current;
        this.props.login(email, pass);
    }

which is ok, but now inside of my IProps I should declare login.

And I can't figure out how to do it?

As an example

    interface IProps {
      login: (u: any, p: any) => any,
      errorMessage: ''
    }

obviously those anys are no good, and need to be replaced with something better. How do I specify that I am in fact going to be passing a react ref here?

4
  • 1
    login: (u: HTMLInputElement, p: HTMLInputElement) => void Commented May 13, 2019 at 13:43
  • ok - I thought the ref was a wrapping type that gave me some other properties, although I have to admit I didn't have any particular reason for that supposition. Commented May 13, 2019 at 13:47
  • ok that works, thanks! Commented May 13, 2019 at 13:49
  • oh of course I'd forgotten that "When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property." reactjs.org/docs/refs-and-the-dom.html Commented May 13, 2019 at 17:21

1 Answer 1

0

Declare in constructor() as,

 constructor(props?) {
        super(props);
        this.emailRef = React.createRef();
        this.passRef = React.createRef();
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Why? what is the necessity to define refs in the constructor? thought the question is not what you have answered
Yes correct, never used ref in class, always using in FC, but technically both work :)
in typescript using this.emailRef inside the constructor gives me error S2339: Property 'emailRef' does not exist on type 'THE COMPONENT TYPE'

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.