Answer the question
In order to leave comments, you need to log in
What types to give when passing a ref to a component?
I have a component to which I pass ref :
export default class NameInput extends React.Component<Record<string, never>> {
constructor(props: Record<string, never>) {
super(props);
}
render() {
return (
<>
<label htmlFor="formName" className="form__label">
Name:
</label>
<input
ref={this.props.ref}
minLength={4}
type="text"
id="formName"
name="name"
className="form__input"
/>
</>
);
}
}
export default class Form extends React.Component {
nameInput: React.RefObject<HTMLInputElement>;
constructor(props: Record<string, never>) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.nameInput = React.createRef();
}
handleSubmit(event: React.FormEvent) {
event.preventDefault();
}
render() {
return (
<>
<Head />
<div className="form">
<form action="#" id="form" className="form__body" onSubmit={this.handleSubmit}>
<div className="form__item">
<NameInput ref={this.nameInput} />
</div>
<div className="form__item">
<RadioInput />
</div>
<div className="form__item">
<DateInput />
</div>
<div className="form__item">
<Continent />
</div>
<div className="form__item">
<PinPhoto />
</div>
<div className="form__item">
<Checkbox />
</div>
<SubmitButton />
</form>
</div>
</>
);
}
}
Answer the question
In order to leave comments, you need to log in
Your ref is taken not from the HTML element inside the component, but from the ref of your NameInput component, which is why TS swears at types. The ref property is reserved for specifying the ref of a particular component, and does not float down in props. To get the element's html ref from inside the NameInput component, you can use one of the options:
1) Change the name of the prop, because the current ref name is already reserved by React to indicate the component 's ref,
in which case the props.refInput link will be available inside the component.
2) Use ref forwarding via React.forwardRef (see the doc below). I don't remember if it's as convenient to work with it in class components as it is in functional components.
Here is more information
<NameInput refInput={this.nameInput} />
https://ru.reactjs.org/docs/forwarding-refs.html I advise you to read the whole.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question