I have a parent component : SiteAdd, and inside, I have a radioIcon custom component, that should send a a site_kind
param to SiteAdd form.
The parent SiteAdd
:
return (
<Fragment>
<ColumnWithPaddingTop>
<SingleColumnPage>
<form onSubmit={handleSubmit(submit)}>
<Checkbox
{...three_phase}
label={I18n.t('three-phase site')}
position='right'
/>
<SiteKind {...useField('site_kind')}/>
<Submit state={state}/>
</form>
</SingleColumnPage>
</ColumnWithPaddingTop >
</Fragment>
The child SiteKind
:
function onTrigger(event) {
console.log('changed');
this.props.parentCallback('Data from child');
event.preventDefault();
}
function SiteKind() {
const { useField } = useForm({ three_phase: false });
const site_kind = useField('site_kind');
return (
<SquaredCheckboxOrRadioRow label={I18n.t('site kind')} {...site_kind} onChange = {onTrigger}>
<Radio
choice='residential' {...site_kind}
content={<RadioContent label={I18n.t('residential')} />}
/>
<Radio
choice='tertiary' {...site_kind}
content={<RadioContent label={I18n.t('tertiary')} />}
/>
</SquaredCheckboxOrRadioRow>
);
}
I cannot receive the value of site_kind
in parent form.
Also, in the child, the onTrigger()
method is never called. Why ? How should I pass the value to parent form ?
CodePudding user response:
The solution is to lift state up.
Put the state inside the parent component and pass the value and setter to the child component as props.
function Parent() {
const { useField } = useForm({ three_phase: false });
const site_kind = useField('site_kind');
// you now have access to `site_kind` in the parent
return <Child site_kind={site_kind} />
}
function Child({ site_kind }) {
// whatever you had before, but `site_kind` is coming from props
}