Reputation: 41
I am trying to set focus an input.password
field. Is it possible?
I didnt see any information on antd docs. I wonder if its possible
Input(Input.TextArea)
has a Input(textAreaRef)
property through ref. but in Input.Password
, I can't find anything about this. Is there a way to accomplish my question?
Upvotes: 4
Views: 27584
Reputation: 51
Sometimes you point with ref to Component instead of DOM-element, so, try this:
In case of Input component from antd library:
import React, { useRef, useEffect } from "react";
import { Input, Form } from "antd";
import "antd/dist/antd.css";
const MyComponent = () => {
// Same as React.createRef()
const passwordInput = useRef(null);
useEffect(() => {
if (passwordInput.current) {
// or, if Input component in your ref, then use input property like:
// passwordInput.current.input.focus();
passwordInput.current.focus();
}
}, [passwordInput]);
return (
<Form>
<Form.Item name="login">
<Input type="text" placeholder="Login" />
</Form.Item>
<Form.Item name="password">
<Input type="password" placeholder="Password" ref={passwordInput} />
</Form.Item>
</Form>
);
};
export default MyComponent;
In case of DOM Element
import React, { useRef, useEffect } from "react";
const MyComponent2 = () => {
const passwordInput = useRef(null);
useEffect(() => {
if (passwordInput.current) {
passwordInput.current.focus();
}
}, [passwordInput]);
return (
<form>
<input type="text" placeholder="Login" />
<input type="password" placeholder="Password" ref={passwordInput} />
</form>
);
};
export default MyComponent2;
This is example on codesandbox
P.S. useEffect hook works almost same as componentDidMount in Class component
Upvotes: 5
Reputation: 63
You can also use refs for Input.password.
import React, { Component } from 'react'
export default class container extends Component {
constructor(props) {
super(props);
this.password = React.createRef();
}
componentDidMount() {
this.password.current.focus();
}
render() {
return (
<div>
<input type="password" ref={this.password}/>
</div>
)
}
}
Refs provide a way to access DOM nodes or React elements created in the render method.
Upvotes: 3
Reputation: 3777
Password inputs are no different than other text inputs. First you must create a reference to the input, then you can call its focus()
method at any point to focus the input. The code below focuses the input when the component mounts:
import React from "react";
import ReactDOM from "react-dom";
import { Icon, Input } from "antd";
import "antd/dist/antd.css";
import "./index.css";
class LoginForm extends React.Component {
passwordInput = null;
componentDidMount() {
this.passwordInput.focus();
}
render() {
return (
<div className="App">
<Input
prefix={<Icon type="lock" style={{ color: "rgba(0,0,0,.25)" }} />}
type="password"
placeholder="Password"
ref={input => {
this.passwordInput = input;
}}
/>
</div>
);
}
}
ReactDOM.render(<LoginForm />, document.getElementById("root"));
Upvotes: 6