I have a category tree and I want to add a subcategory to it by the “+” button shown inside the subcategory in the picture below.
my problem is I want to add this subcategory to the specific “cloths” category for example, not to all categories, I have an idea of using the category ID I can’t figure out how to do it!
I’ve written this code so far! and I am using JSON-server for fake API calls as follows:
import { Formik, Field, Form } from 'formik';
import React, { useEffect } from 'react';
import { getData, postDataDefaultHeader } from '../../Services/Api';
import Modal from '../Modal/Modal';
const ManageCategories = () => {
const [categories, setCategories] = React.useState(false);
const [isSubmit, setIsSubmit] = React.useState(false);
const [addButton, setAddButton] = React.useState(false);
useEffect(() => {
getData(`${process.env.REACT_APP_API}/categories`, setCategories);
if (isSubmit) {
getData(`${process.env.REACT_APP_API}/categories`, setCategories);
setIsSubmit(false);
}
}, [isSubmit]); //only get categories data when categories is truthy
return (
<div>
<Formik
initialValues={{
categoryName: '',
}}
onSubmit={(values) =>
postDataDefaultHeader(
`${process.env.REACT_APP_API}/categories`,
values
)
}
>
{({ values }) => (
<Form>
<Field
name="categoryName"
type="text"
placeholder={'add new category'}
/>
<button onClick={() => setIsSubmit(true)} type="submit">
save
</button>
</Form>
)}
</Formik>
<div>
{categories &&
categories.map((category) => (
<dl key={category.categoryName}>
<dt>{category.categoryName}</dt>
{category.subCategory &&
category.subCategory.map((subCate) => (
<dd
key={subCate.subCategoryName}
value={subCate.subCategoryName}
>
{subCate.subCategoryName}
<div>
<button
onClick={(id) => {
if (id === category.id) {
setAddButton(!addButton);
}
}}
>
+
</button>
{addButton && (
<div>
<input type="text" /> <button>حفظ</button>
</div>
)}
</div>
</dd>
))}
</dl>
))}
</div>
</div>
);
};
export default ManageCategories;