Below is my parent component with multiple inputs from a loop. How can I choose one input
to focus? Do I have to create a dynamic ref
in this case?
You can use callback refs to generate and store the dynamic ref of each input in an array. Now you can refer to them using the index of the ref:
const Hello = React.forwardRef((props, ref) => );
class Button extends React.Component {
onClick = () => this.props.onClick(this.props.id);
render() {
return (
);
}
}
class TestRef extends React.Component {
state = {
data: [
{
name: "abc"
},
{ name: "def" }
]
};
inputRefs = [];
setRef = (ref) => {
this.inputRefs.push(ref);
};
focusInput = (id) => this.inputRefs[id].focus();
render() {
return (
{this.state.data.map(({ name }) => (
))}
);
}
}
ReactDOM.render( , document.getElementById("root"));