I am trying to use formic and yup with react. In this project the selection button was created in a separate component using React Select. The attributes of the select tag are sending as the props. When I select an option in the selection tag, this error is occurred.
× Error: Objects are not valid as a React child (found: object with keys {id}). If you meant to render a collection of children, use an array instead.
Yup validation method
country: Yup.object({id: Yup.string().required('Please select a country'),}),
Initial data:
const formik = useFormik({
initialValues: {
country: {}
}
})
This is options
const countryOptions = [
{ id:"1", value: "india", label: "India" },
{ id:"2", value: "sri lanka", label: "Sri Lanka" },
{ id:"3", value: "us", label: "US" },
];
Using selection
<XSearchSelect
label="Country"
options={countryOptions}
id="country"
name="country"
onBlur={()=>{
formik.handleBlur({ target: {name:'country'} });
}}
onChange={(option) => {formik.setFieldValue("country",option.id);}}
error={formik.errors.country}
touched={formik.touched.country}
/>
Customized selection component
import React from 'react'
import Select from 'react-select'
const XSearchSelect = ({ value, onChange, options, label,error,onBlur,id,name,touched }) => {
return (
<div>
<div className="block text-xaplink_gray_3 text-sm font-bold mb-2">{label}</div>
<Select
isClearable="true"
value={value}
options={options}
onChange={onChange}
id={id}
name={name}
onBlur={onBlur}
theme={theme => ({
...theme,
borderRadius: 5,
colors: {
...theme.colors,
primary25: 'silver',
primary50: 'gray',
primary: 'black',
},
})
}
/>
{touched && error ? (
<p className='text-xs pl-2 text-xaplink_red_2 mb-4'>{error}</p>
) : null}
</div>
)
}
export default XSearchSelect
CodePudding user response:
The issue you have here is that you try to render your error
here:
<p className='text-xs pl-2 text-xaplink_red_2 mb-4'>{error}</p>
But it is an object, as you have described it in your initial values. You probably want to pass error={formik.errors.country.id}
to your <XSearchSelect />
component.
Or, as an another option you can just store country's ID as string in Formik, like this:
const formik = useFormik({
initialValues: {
country: ""
}
})
This way you previous code should work some updates, adhering to the fact that you're storing ID as a string and not as an object now.