Using @user9408899's answer as a guide and reading up, I came up with the following solution (only showing parts of the code directly relevant to the solution).
Parent component
- Implemented an
inputRefToFocus property to store the ref which we
want to add focus to.
- Implemented
setInputRefToFocus(ref) to assign the property above in the state, also passed this and inputRefToFocus to the child component.
export class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
...
// this is the ref for the input field to focus on
// when modal window appears, depending on button clicked,
// we want to focus on the field user was editing
inputRefToFocus: null
};
this.setInputRefToFocus = this.setInputRefToFocus.bind(this);
}
setInputRefToFocus(ref) {
this.setState({ inputRefToFocus: ref });
}
render() {
{ rows.map(elem => (
<PivotTableRow
setInputRefToFocus={this.setInputRefToFocus}
inputRefToFocus={this.state.inputRefToFocus}
/>
)) }
}
}
Child Component
When the input elements are created, each one is added to the array of refs.
When the input is focused, we set its ref in the parent component's inputRefToFocus property.
- Set the focus in
componentDidUpdate()
export class Child extends React.Component {
constructor(props) {
super(props);
this.state = {
...
};
this.inputRef = [];
}
componentDidUpdate(prevProps) {
if (this.props !== prevProps) {
if (this.inputRef[this.props.inputRefToFocus] !== undefined) {
this.inputRef[this.props.inputRefToFocus].focus();
}
}
}
render() {
return (
// loop to generate input elements
<Input
ref={el => { this.inputRef[dummyvalue] = el; }
onChange={...}
onFocus={() => this.props.setInputRefToFocus(dummyvalue)}
/>
);
}
}
I feel like the code could be improved significantly as it was my first stab at it