I'm learning react and I am stuck. I am trying to share a form between Edit and Create components. I am having a really hard time figuring out what I am doing wrong to initialize the values of the checked property for the radio group. After the page loads I can toggle the radio buttons. Initially, however, neither is checked.
I'm starting to think I am setting up my checked property incorrectly on the form.
Edit component (forms parent component) :
class CompanyMasterEdit extends React.Component {
componentDidMount() {this.props.fetchCompany(this.props.match.params.companyId,this.props.match.params.companyName)}
onSubmit = (formValues) => { this.props.editCompany(this.props.match.params.companyId, formValues) }
render() {
return (
<div style={{ padding: 50 }}>
<h1 style={{ textAlign: "center" }}>Edit Company Master Record</h1>
<h5 style={{ textAlign: "center" }}>
<span style={{ color: "red" }}>*</span> indicates required field
</h5>
<CompanyMasterForm
initialValues={_.pick(
this.props.company,
"isKeyCompany",...
)}
onSubmit={this.onSubmit}
/>
const mapStateToProps = (state, ownProps) => {
return { company: state.companies[ownProps.match.params.companyId] }
}
export default connect(mapStateToProps, { fetchCompany, editCompany })( CompanyMasterEdit)
Form:
class CompanyMasterForm extends React.Component {
<form
className="ui form error"
onSubmit={this.props.handleSubmit(this.onSubmit)}
>
<Field
label="Is This a Key Company?"
component={RadioGroup}
name="isKeyCompany"
required={true}
options={[
{ title: "Yes", value: true },
{ title: "No", value: false },
]}
checked={this.props.initialValues.isKeyCompany}
// onClick={this.setIsKeyCompany}
//onClick={(e) => this.setState({ isKeyCompany: e.target.checked })}
onClick={() => {this.setState((prevState) => {return {checked: !this.props.initialValues.isKeyCompany,}})
}}
/>
<button className="ui button primary">Submit</button>
</form>
RadioButtonGroup as a separate component:
class RadioGroup extends React.Component {
render() {
return (
<div className={className}>
<div className="inline fields">
<div className={labelClassName}>
<label>{label}</label>
</div>
{options.map((o) => {
const isChecked = o.value ? "true" : "false"
console.log("o.value :", o.value)
return (
<label key={o.title}>
<input
type="radio"
{...input}
value={o.value}
checked={isChecked === input.value}
/>
{o.title}
</label>
)
})}
</div>
</div>
)
}
}
// const mapStateToProps = (state) => {
// console.log("radio group state : ", state)
// return { isKeyCompany: state.form.companyMasterForm.values.isKeyCompany }
// }
// export default connect(mapStateToProps)(RadioGroup)
// export default connect(null)(RadioGroup)
export default RadioGroup
I have a codesandbox up. I feel like I'm close and dancing all around it but I can't get it. Any help is appreciated.