Problem:
I have an array of formInputItems with a defaultValue, and when I map throught these I would like to convert the defaultValue to a dynamic value as it recognizes it as a string. So instead of getting back the actual movie title, I get back movie.title as it is in the object. The movie object is passed down as a prop to cardform, how can I make it recognize it? So when I map through formInputItems I want it to recognize defaultValue={${movie.plot}
} and not defaultValue=’movie.plot’
I have an array of objects for the input:
string.js
export const formInputItems = [
{
label: 'title',
defaultValue: 'movie?.title',
},
{
label: 'plot',
defaultValue: 'movie?.plot',
},
]
the mapping:
const CardForm = ({ movie }: CardFormProps) => {
const router = useRouter();
const {
isEditing,
setIsEditing,
formData,
setFormData,
openForm,
setOpenForm,
} = useGlobalContext();
return (
<div className='w-full h-full bg-black/80 backdrop-blur-md absolute top-0 left-0 flex items-center justify-center'>
<form
onSubmit={submitHandler}
className='bg-primary p-10 max-w-[450px] w-full flex flex-col gap-4 rounded-md'>
<TitleTwo>{isEditing ? 'Edit Movie' : 'Add Movie'}</TitleTwo>
{formInputItems.map(({ label, defaultValue }, index) =>
isEditing && (
<EditInput
key={index}
htmlFor={label}
id={label}
defaultValue={defaultValue}
onChange={(e: any) => onChangeHandler(e, label)}>
{label}
</EditInput>
)
)}
</form>
</div>
);
};
export default CardForm;
Solution:
Control with dynamic variables is almost impossible since it needs to be defined first. On the other hand, controlling property of object dynamically is possible.
export const formInputItems = [
{
label: 'title',
defaultValue: 'title',
},
{
label: 'plot',
defaultValue: 'plot',
},
]
const CardForm = ({ movie }: CardFormProps) => {
const router = useRouter();
const {
isEditing,
setIsEditing,
formData,
setFormData,
openForm,
setOpenForm,
} = useGlobalContext();
return (
<div className='w-full h-full bg-black/80 backdrop-blur-md absolute top-0 left-0 flex items-center justify-center'>
<form
onSubmit={submitHandler}
className='bg-primary p-10 max-w-[450px] w-full flex flex-col gap-4 rounded-md'>
<TitleTwo>{isEditing ? 'Edit Movie' : 'Add Movie'}</TitleTwo>
{formInputItems.map(({ label, defaultValue }, index) =>
isEditing && (
<EditInput
key={index}
htmlFor={label}
id={label}
defaultValue={movie[defaultValue]}
onChange={(e: any) => onChangeHandler(e, label)}>
{label}
</EditInput>
)
)}
</form>
</div>
);
};
export default CardForm;
You might receive type error when using movie[defaultValue]
so you should define or casting type