I am working with forms in react.
The challenge I am facing is whenever i set an onchange handler for the input field, it changes the value for all the input fields I have.
Form input fields are mapped and are coming from the api. What I want is a generic on change handler to manage all the input fields.
import React, { Component } from "react";
import {
TextInputComponent,
RadioInputComponent,
SelectComponent,
} from "../../components/index";
import IntlMessages from "../../common/constants/IntlMessages";
class DummyForm extends Component {
constructor(props) {
super(props);
this.state = {
field: "",
checkBox: "",
options: "",
radioField: "",
error: "",
};
}
componentDidMount() {
const code = window.location.pathname.split("/")[2];
this.props.getEmsForms(code);
}
//this my on change handler and it would be great help if someone can tell where iam wrong.
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
})
}
submit = () => {
const { field, checkBox, options, radioField } = this.state;
const auth = this.props.user.data.user.access_token;
this.props.updateEmailPhone({
email,
address,
auth,
});
};
render() {
return (
<React.Fragment>
<div className="row justify-content-center py-2 my-2">
<div className="col-sm-12 col-lg-5 col-md- border border-info bg-light">
<div className="row p-3">
{this.props.getForms.data
? this.props.getForms.data.map((item) => {
return (
<div className="col-12 p-2">
{item.inputType == "textbox" ? (
<TextInputComponent
key={item.fieldName}
label={item.fieldLabelText}
type="text"
placeholder={item.fieldName}
value={this.state.field}
onChange={(e) =>
this.handleChange(e, "field")
}
/>
) : item.inputType == "dropdown" ? (
<>
<label>{item.fieldLabelText}</label>
<select
className="custom-select "
id="inputGroupSelect01"
onChange={(e) =>
this.handleChange({ options: e.target.value })
}
>
{item.inputOptions.map((key) => (
<option>{key.value}</option>
))}
</select>
</>
) : item.inputType == "checkbox" ? (
<SelectComponent
name={"select2"}
value={this.state.checkBox}
label={item.fieldLabelText}
onChange={(e) =>
this.setState({ checkBox: e.target.value })
}
/>
) : item.inputType == "radio" ? (
<RadioInputComponent
title="gender"
value={this.state.gender}
name={item.fieldLabelText}
onChange={(e) => {
this.setState({ radioField: e.target.value });
}}
/>
) : null}
</div>
);
})
: this.props.getForms.messages}
<div className="row" style={{ marginTop: "50px" }}>
{/* <div className="col d-flex justify-content-start">
<button className="btn-danger" onClick={this.toggleModal}>
Ja
</button>
</div> */}
{this.props.getForms.data && (
<div className="col d-flex justify-content-end">
<button className="btn btn-success button-margin">
<IntlMessages id="blank.button" />
</button>
</div>
)}
</div>
</div>
</div>
</div>
</React.Fragment>
);
}
}
export default DummyForm;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…