I am generating a new field on every click of a button which is disabled by default. I click on the edit button to toggle the property of disabled and it works, however I am not able to set focus on the input itself when I click the Edit button.
Please advise.
This is what I have:
import React, { useReducer, useRef, useEffect } from "react";
import { get, map, reject } from "lodash";
import { Row, Col } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
const initialState = {
fields: []
};
export default function App() {
const [state, setState] = useReducer(
(state, newState) => ({
...state,
...newState
}),
initialState
);
const fieldInputRef = useRef(null);
useEffect(() => {
if (fieldInputRef.current) {
fieldInputRef.current && fieldInputRef.current.focus();
}
}, [fieldInputRef.current]);
const addNewField = () => {
setState({
fields: state.fields.concat({
id: state.fields.length + 1,
editable: false,
fieldName: `field${state.fields.length + 1}`,
fieldValue: ""
})
});
};
const onHandleInputChange = (event, id) => {
const newFieldsList = map(state.fields, (item) => {
if (item.id === id) {
item.fieldValue = event.currentTarget.value;
}
return item;
});
setState({ fields: newFieldsList });
};
const handleInputBlur = (id) => {
const newFieldsList = map(state.fields, (item) => {
if (item.id === id) {
item.editable = false;
}
return item;
});
setState({ fields: newFieldsList });
};
const handleFieldEdit = (i) => {
const result = map(state.fields, (item) => {
item.editable = item.id === i;
return item;
});
fieldInputRef.current && fieldInputRef.current.focus();
setState({
fields: result
});
};
const handleFieldDelete = (i) => {
setState({
fields: reject(state.fields, { id: i })
});
};
return (
<div className="App">
{state.fields.map((item) => (
<Row key={item.id} className="mb-2">
<Col md={2}>
<div style={{ border: `1px solid blue` }}>{item.id}</div>
</Col>
<Col md={8}>
<input
disabled={!get(item, "editable")}
onChange={(event) => onHandleInputChange(event, item.id)}
value={item.fieldValue}
name={item.fieldName}
onBlur={() => handleInputBlur(item.id)}
ref={fieldInputRef}
/>
</Col>
<Col md={1}>
<button onClick={() => handleFieldEdit(item.id)}>Edit</button>
</Col>
<Col md={1}>
<button onClick={() => handleFieldDelete(item.id)}>Delete</button>
</Col>
</Row>
))}
<button onClick={addNewField}>Add new field</button>
</div>
);
}
This is my codesandbox link
question from:
https://stackoverflow.com/questions/65939909/adding-focus-to-a-dynamically-created-input-onclick-of-a-button-reactjs 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…