Reputation: 583
I am trying to build a form-wizard. I set up the wizard via react-router
and used formik
for the forms. Now I ran into a problem while creating a customizable radio-button. I used the react-custom-radio
library for that.
When I use the radio-buttons outside of the routes, it is working as it should (code at the bottom of the post).
When I use the with the router, the props are passed down to the child component:
<Route path="/form/location" render={(props) => (<Pricing {...props} />)} />
Inside the child component, I access the props the same way, as I did it in the parent, where it worked.
const Pricing = (props) => {
const {
values,
touched,
errors,
setFieldValue,
setFieldTouched,
} = props;
return (
<div>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</div>
);
}
But now I always get the error Cannot read property 'car' of undefined
.
Why doesn't it work if there's a router in between?
If I do it like that, it works:
<Form>
<Switch>
<Redirect from="/" exact to="/form/location" />
<Route path="/form/location" render={(props) => (<Pricing {...props} />)} />
</Switch>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</Form>
Upvotes: 3
Views: 5469
Reputation: 1096
And if you need both Formik's props and this component's you could do:
render={(formikProps) => <Pricing {...formikProps}, {...props} />}
That will create a long list of attributes from both props for Pricing to use.
Upvotes: 2
Reputation: 112897
The props
given to the render
function are the route props listed in the documentation. What you want to do in this case is to pass down the props
from the parent component, not the route props:
class ParentComponent extends React.Component {
render() {
const { props } = this;
const {
values,
touched,
errors,
setFieldValue,
setFieldTouched,
} = props;
return (
<Form>
<Switch>
<Redirect from="/" exact to="/form/location" />
<Route
path="/form/location"
render={() => <Pricing {...props} />}
/>
</Switch>
<MyRadio
value={values.car}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.car}
touched={touched.car}
/>
</Form>
);
}
}
Upvotes: 2