antd steps custom props array in react - reactjs

I have question and need some help,
currently I'm creating website using reactjs and antd, I'm trying to create reusable antd steps components, and I want to pass props as array, and using the props as the content of antd steps, here is my code
const [current, setCurrent] = useState(0);
const [steps, setSteps] = useState([
{
title: "Info Dasar",
content: "halo",
},
{
title: "Alamat & Koordinasi",
content: <div>yuhu</div>,
},
{
title: "Whatsapp Settings",
content: <div>yuhu</div>,
},
]);
const classes = useStyles();
const next = () => {
setCurrent(current + 1);
};
const prev = () => {
setCurrent(current - 1);
};
// console.log(itemContent);
const items = steps.map((item) => ({
key: item.title,
title: item.title,
}));
return (
<>
<Steps
current={current}
labelPlacement="vertical"
className={classes.root}
items={items}
type="primary"
// direction='vertical'
/>
<div>{steps[current].content}</div>
<div className={classes.buttonContainer}>
{current < steps.length - 1 && (
<Buttons
text="Selanjutnya"
containerClass="mt-[20px] w-[186px] h-[48px]"
customClass="btn-primary btn-large"
onClick={() => next()}
/>
)}
{current > 0 && (
<Buttons
text="Sebelumnya"
containerClass="mt-[20px] w-[186px] h-[48px]"
customClass="btn-primary btn-large"
onClick={() => prev()}
/>
)}
{current === steps.length - 1 && (
<Buttons
text="Submit"
containerClass="mt-[20px] w-[186px] h-[48px]"
customClass="btn-primary btn-large"
onClick={() => message.success("Processing complete!")}
/>
)}
</div>
</>
);
and here what I try to pass as props
const StepsDoc = () => {
return (
<StepsComponent
currentSteps={0}
itemContent={[
{
title: "Info Dasar",
content: "halo",
},
{
title: "Alamat & Koordinasi",
content: <div>yuhu</div>,
},
{
title: "Whatsapp Settings",
content: <div>yuhu</div>,
},
]}
/>
);
};

Related

ReactJS Redux toolkit Component does not update, only after refreshing the page

Im using Redux-toolkit (already using it for a while). When I reset my redux store, and load my website for the first time the SharedList component does not update if I update the store.
But the strange thing... after refreshing the page, everything works perfect!
Im using the [...array] and Object.assign({}) methods. Also console logged, and the objects are NOT the same.
this is the reducer: (Only updates the ReactJS component after I refresh my page)
CREATE_SHARED_LIST_ITEM_LOCAL: (
proxyState,
action: PayloadAction<{
active: boolean;
checked: boolean;
id: string;
text: string;
}>
) => {
const state = current(proxyState);
const [groupIndex, group] = getCurrentGroupIndex(state);
const { id, text, active, checked } = action.payload;
const listItemIndex = group.shared_list.findIndex((item) => {
return item.id === id;
});
const group_id =
proxyState.groups[groupIndex].shared_list[listItemIndex].group_id;
const sharedItem: SharedListItem = {
text,
id,
checked,
active,
group_id,
};
proxyState.groups[groupIndex].shared_list[listItemIndex] = Object.assign(
{},
sharedItem
);
},
This is the ReactJS component
const GroceryList: React.FC = () => {
const [update, setUpdate] = useState(false);
const handleUpdate = () => {};
const dispatch = useDispatch();
const listItems = useSelector(selectSharedList);
const { setTitle } = useContext(HeaderContext);
const editItem = async (
id: string,
checked: boolean,
text: string,
active: boolean
) => {
dispatch(MUTATE_SHARED_LIST_LOCAL({ id, text, active, checked }));
};
const fetchList = async () => {
await dispatch(QUERY_SHARED_LIST({}));
};
useEffect(() => {
setTitle("Lijst");
fetchList();
}, []);
const list = listItems.filter((item) => {
return item.active;
});
return (
<>
<Card
// style={{
// paddingBottom: 56,
// }}
>
<CardContent>
<List>
{list.length === 0 ? (
<Box textAlign="center" justifyContent="center">
{/* <Center> */}
<Box>
<EmptyCartIcon style={{ width: "45%" }} />
</Box>
{/* </Center> */}
<Typography>De gedeelte lijst is leeg</Typography>
</Box>
) : null}
{list.map((item, index) => {
const { checked, text, id, active } = item;
return (
<ListItem dense disablePadding key={"item-" + index}>
<Checkbox
checked={checked}
onClick={() => {
editItem(id, !checked, text, active);
}}
/>
<EditTextSharedListItem item={item} />
<Box>
<IconButton
onClick={() => {
editItem(id, checked, text, false);
}}
>
<DeleteOutlineRoundedIcon />
</IconButton>
</Box>
</ListItem>
);
})}
</List>
</CardContent>
</Card>
<AddSharedListItem />
</>
);
};
This is the selector
export const selectSharedList = (state: RootState) => {
const group = selectCurrentGroup(state);
return group.shared_list.filter((item) => {
return item.active;
});
};

Ant Design cannot update initial Value for dynamic Form Item

I am using Ant Design 4 to make a dynamic form like this: there is an "Add form item" button, when you click it, you can add a select box to your form. After selecting one option from that select box, there will be some inputs with an initial value based on the selected value data. My problem is these inputs fields only render one time when selecting one value from the select box for the first time. I have logged the "item" data inside infoData[0]?.map((item, index), it returns with the right value but the Form Inputs do not update their initialValue. Here is my code:
import React, { useState, useCallback } from "react";
import { Button, Form, Select, Input } from "antd";
const FormPage = () => {
const [userData, setUserData] = useState([]);
const [optionList, setOptionList] = useState([
{
name: "Option 1",
value: "o-1",
info: [
{ name: "Option 1 Info 1", point: 11 },
{ name: "Option 1 Info 2", point: 12 },
],
},
{
name: "Option 2",
value: "o-2",
info: [
{ name: "Option 2 Info 1", point: 13 },
{ name: "Option 2 Info 2", point: 14 },
],
},
]);
const onSubmitForm = (values: object) => {
console.log(values);
};
const addUserData = () => {
const newData = {
id: Math.random().toString(36).substring(7),
userName: Math.random().toString(36).substring(7),
};
setUserData([...userData, newData]);
};
const selectedOption = (val) => {
const selectedData = optionList.filter((item) => item.value === val);
return selectedData[0].info;
};
return (
<Form onFinish={onSubmitForm}>
<p>
<Button onClick={addUserData}>Add Form Item</Button>
</p>
{userData.length > 0
? userData.map((item, index) => (
<FormPageItem
key={index}
data={item}
index={index}
addUserData={addUserData}
optionList={optionList}
selectedOption={selectedOption}
/>
))
: ""}
<Button type="primary">Submit</Button>
</Form>
);
};
const FormPageItem = (props) => {
const [infoData, setInfoData] = useState([]);
const handleSelectOption = (value) => {
const selected = props.selectedOption(value);
console.log("selected", selected);
const newData = [...infoData];
newData[0] = selected;
console.log(newData);
setInfoData(newData);
};
const renderInput = useCallback(() => {
if (infoData.length > 0) {
return (
<>
{infoData[0]?.map((item, index) => (
<Form.Item
name={[`option-${props.data.id}`, `user-info-${index}`]}
style={{ marginBottom: 16 }}
initialValue={item.name}
key={index}
>
<Input />
</Form.Item>
))}
</>
);
}
return "";
}, [infoData]);
return (
<div>
<Form.Item
name={[`option-${props.data.id}`, "options"]}
label="Option List"
>
<Select showArrow={false} onChange={handleSelectOption}>
{props.optionList.map((item) => (
<Select.Option value={item.value} key={item.value}>
{item.name}
</Select.Option>
))}
</Select>
{renderInput()}
</Form.Item>
</div>
);
};
export default FormPage;
Please see the documents here ant design form documents:
Note that initialValues cannot be updated by setState dynamically, you should use setFieldsValue in that situation.
In your case, you can just replace renderInput function with simple render function, and even no need of onChange function for the first Select component.
const FormPageItem = (props) => {
const [infoData, setInfoData] = useState([]);
return (
<div>
<Form.Item
name={[`option-${props.data.id}`, "options"]}
label="Option List"
>
<Select showArrow={false} >
{props.optionList.map((item) => (
<Select.Option value={item.value} key={item.value}>
{item.name}
</Select.Option>
))}
</Select>
{/* {renderInput()} */}
</Form.Item>
<Form.Item
dependencies={[[`option-${props.data.id}`,"options"]]}
>
{({getFieldValue})=>{
const v = getFieldValue([`option-${props.data.id}`,"options"])
if(!v){return null}
const selected = props.selectedOption(v);
return (
<>
{selected?.map((item, index) => (
<Form.Item
name={[`option-${props.data.id}`, `user-info-${index}`]}
style={{ marginBottom: 16 }}
initialValue={item.name}
key={index}
>
<Input />
</Form.Item>
))}
</>
)
}}
</Form.Item>
</div>
);
};

How can i close the Action menu when one clicks outside the component anywhere

i have an component to edit a table data what i want is when i click anywhere outside that component that component must be closed so what i have done till mow is as below
this is my parent component in which i have used that edit modal to show when click on it
import React, { useState, useEffect, useRef } from 'react';
import ActionMenu from './ActionMenu';
export default function DashBoard(props) {
const columns = [
{
Header: 'Name',
accessor: 'patient.name',
Cell: (props) => <TextSpan>{props.value}</TextSpan>,
},
{
Header: 'Time of Appointment',
accessor: 'datetime',
Cell: (props) => (
<span>{moment(props.value).format('hh:mm A')}</span>
),
},
{
Header: 'Actions',
Cell: ({ row }) => (
<ActionMenu
{...props}
handleAction={handleAction}
row={row.original}
/>
),
},
];
const handleAction = (value) => {
changeAppointment(value).then((result) => {
const newData = Array.from(data);
const matchedIndex = newData.findIndex(
(x) => x.id == result.data.id
);
newData[matchedIndex].status = result.data.status;
setData(newData);
});
};
useEffect(() => {
debounceSearch(search);
}, [search]);
}
and this is my child component
import React, { useState } from 'react';
import PostPone from 'Components/Modal';
export default function ActionMenu(props) {
const { row, handleAction } = props;
const [IsMenuOpen, setMenuOpen] = useState(false);
const [time, setTime] = useState(null);
const [isModalOpen, setModalOpen] = useState(false);
return (
<MainDiv>
<ActionDiv>
{row.status.toLowerCase() === 'confirmed' ? (
<ActionItem noPaddingLeft title="Come Now">
<ComeNow
onClick={() =>
handleAction({ id: row.id, status: 'inside' })
}
/>
</ActionItem>
) : row.status.toLowerCase() === 'inside' ? (
<ActionItem noPaddingLeft title="Mark as visited">
<Approved
onClick={() =>
handleAction({ id: row.id, status: 'visited' })
}
/>
</ActionItem>
) : (
<ActionItem>{<EmptyDiv />}</ActionItem>
)}
<ActionItem title={'Send Notification'}>
<SendNotification />
</ActionItem>
<ActionItem
title="Menu"
background
open={IsMenuOpen}
onClick={() => setMenuOpen(!IsMenuOpen)}
>
<Dots />
{IsMenuOpen && (
<Menu>
<MenuItem
onClick={() =>
props.history.push(
'/appointments/edit_appointment?id=' +
row.id
)
}
>
<ItemLogo>
<Edit />
</ItemLogo>
<ItemText>Edit</ItemText>
</MenuItem>
<MenuItem
borderBottom
paddingBottom
onClick={() =>
handleAction({
id: row.id,
status: 'denied',
})
}
>
<ItemLogo>
<Close />
</ItemLogo>
<ItemText>Cancel</ItemText>
</MenuItem>
<MenuItem borderBottom paddingBottom paddingTop>
<ItemLogo>
<Delay />
</ItemLogo>
<ItemText>Delay</ItemText>
</MenuItem>
<MenuItem
paddingTop
onClick={() =>
handleAction({
id: row.id,
status: 'inside',
})
}
>
<ItemLogo>
<ComeNowSmall />
</ItemLogo>
<ItemText>Come Now</ItemText>
</MenuItem>
<MenuItem
onClick={() =>
handleAction({
id: row.id,
status: 'visited',
})
}
>
<ItemLogo>
<MarkVisted />
</ItemLogo>
<ItemText>Mark as Visited</ItemText>
</MenuItem>
</Menu>
)}
</ActionItem>
</ActionDiv>
</MainDiv>
);
}
as in image when i click on outside the child component it should close that component any help would be much appreciated thanks in advance
You can use small trick.
You can render div with transparent background with absolute position under your overlay(DropDown). There you can handle click and close your overlay(DropDown).
You need to check what is the element on click event, and if it's not your menu you can execute the close action.
Look this example.

testing conditional rendering that relies on state using react testing library

What would be the way to test a component that relies on the initial state for conditional rendering ?
For example showLessFlag is dependent on state, and testing state in react-testing-library is counter productive.
so how would i test this condition in the CommentList component
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment, this shows by default */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
Should it be test like the following
it("should check more comments", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-show-more");
expect(commentList).toBeNull();
});
But im getting this error because of the conditional rendering
TestingLibraryElementError: Unable to find an element by:
[data-testid="comment-show-more"]
CommentList.tsx
import React, { Fragment, useState, Ref } from "react";
import Grid from "#material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";
function CommentList(props: any, ref: Ref<HTMLDivElement>) {
const [showMore, setShowMore] = useState<Number>(2);
const [openModal, setOpenModal] = useState(false);
const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
const the_comments = props.comments.length;
const inc = showMore as any;
const min = Math.min(2, the_comments - inc);
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
const handleClickOpen = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const showLessComments = (e) => {
e.preventDefault();
setShowMore(2);
setShowLessFlag(false);
};
const isBold = (comment) => {
return comment.userId === props.userId ? 800 : 400;
};
// show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
const filterComments = props.comments
.slice(0)
.sort((a, b) => {
const date1 = new Date(a.createdAt) as any;
const date2 = new Date(b.createdAt) as any;
return date2 - date1;
})
.slice(0, inc)
.reverse();
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div data-testid="comment-show-more" key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
return (
<Grid data-testid="comment-list-div">
<Fragment>
<div style={{ margin: "30px 0px" }}>
{props.comments.length > 2 ? (
<Fragment>
{min !== -1 && min !== -2 ? (
<Fragment>
{min !== 0 ? (
<OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : null}
</div>
</Fragment>
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
</Grid>
);
}
export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
CommentList.test.tsx
import "#testing-library/jest-dom";
import React, { Ref } from "react";
import CommentList from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "#testing-library/react";
const props = {
user: {},
postId: null,
userId: null,
currentUser: {},
ref: {
current: undefined,
},
comments: [
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 520,
postId: 28,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 9,
},
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 519,
postId: 27,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 10,
},
],
deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
it("should render <CommentList/>", () => {
const commentList = render(<CommentList {...props} />);
expect(commentList).toBeTruthy();
});
it("should render first comment", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.firstChild).toBeTruthy();
});
it("should render second child", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-list-div");
expect(commentList.lastChild).toBeTruthy();
});
it("should check comments", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div")).toBeTruthy();
expect(rtl.getByTestId("comment-list-div").querySelectorAll(".comment").length).toEqual(2);
});
it("should match snapshot", () => {
const rtl = render(<CommentList {...props} />);
expect(rtl).toMatchSnapshot();
});
it("should check more comments", () => {
const { getByTestId } = render(<CommentList {...props} />);
const commentList = getByTestId("comment-show-more");
expect(commentList).toBeNull();
});
});
Any getBy* query in react-testing-library will throw an error if no match is found. If you want to test/assert the absence of an element then you want to use any of the queryBy* queries, they return null if no match is found.
Queries
it("should check more comments", () => {
const { queryByTestId } = render(<CommentList {...props} />);
const commentList = queryByTestId("comment-show-more");
expect(commentList).toBeNull();
});
To better answer this question, being that i have more experience with using react testing library now.
When we go about testing for conditions, we need to trigger the action that makes the change to the state.
For example in this situation
We have a condition like showLessFlag
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment, this shows by default */}
{filterComments.map((comment, i) => (
<div key={i} className="comment">
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
In order to properly test this, we need to trigger the event that will change showLessFlag to false.
So we can do something like
<OurSecondaryButton
onClick={(e) => showLessComments(e)}
data-testid="_test-show-less"
component="span"
color="secondary"
>
Show Less Comments
</OurSecondaryButton>
test
it("should trigger showLessComments ", () => {
const { getByTestId } = render(<CommentList {...props} />);
const showLessButton = getByTestId("__test-show-less");
fireEvent.click(showLessButton);
expect(...) // whatever to be called, check for the existence of a div tag, or whatever you want
});
Testing for conditions improves code coverage :)

How to unit test a component that has a ref prop

How do you unit test a component that has a ref prop ? i'm getting this error
● Should render › should render
TypeError: Cannot add property current, object is not extensible
I looked at another question Unit testing React component ref, but there is no solution for that question.
this is the test
CommentList.test.tsx
import "#testing-library/jest-dom";
import React from "react";
import { CommentListComponent as CommentList } from "./CommentList";
import { render, getByText, queryByText, getAllByTestId } from "#testing-library/react";
const props = {
user: {},
postId: null,
userId: null,
currentUser: {},
ref: {},
comments: [
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 520,
postId: 28,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 9,
},
{
author: { username: "barnowl", gravatar: "https://api.adorable.io/avatars/400/bf1eed82fbe37add91cb4192e4d14de6.png", bio: null },
comment_body: "fsfsfsfsfs",
createdAt: "2020-05-27T14:32:01.682Z",
gifUrl: "",
id: 519,
postId: 27,
updatedAt: "2020-05-27T14:32:01.682Z",
userId: 10,
},
],
deleteComment: jest.fn(),
};
describe("Should render <CommentList/>", () => {
it("should render <CommentList/>", () => {
const commentList = render(<CommentList {...props} />);
expect(commentList).toBeTruthy();
});
});
This is the component.
CommentList.tsx
import React, { Fragment, useState, Ref } from "react";
import Grid from "#material-ui/core/Grid";
import OurSecondaryButton from "../../../common/OurSecondaryButton";
import CommentListContainer from "../commentListContainer/commentListContainer";
function CommentList(props: any, ref: Ref<HTMLDivElement>) {
const [showMore, setShowMore] = useState<Number>(2);
const [openModal, setOpenModal] = useState(false);
const [showLessFlag, setShowLessFlag] = useState<Boolean>(false);
const the_comments = props.comments.length;
const inc = showMore as any;
const min = Math.min(2, the_comments - inc);
const showComments = (e) => {
e.preventDefault();
if (inc + 2 && inc <= the_comments) {
setShowMore(inc + 2);
setShowLessFlag(true);
} else {
setShowMore(the_comments);
}
};
const handleClickOpen = () => {
setOpenModal(true);
};
const handleCloseModal = () => {
setOpenModal(false);
};
const showLessComments = (e) => {
e.preventDefault();
setShowMore(2);
setShowLessFlag(false);
};
const isBold = (comment) => {
return comment.userId === props.userId ? 800 : 400;
};
// show comments by recent, and have the latest comment at the bottom, with the previous one just before it.
const filterComments = props.comments
.slice(0)
.sort((a, b) => {
const date1 = new Date(a.createdAt) as any;
const date2 = new Date(b.createdAt) as any;
return date2 - date1;
})
.slice(0, inc)
.reverse();
const showMoreComments = () => {
return filterComments.map((comment, i) => (
<div key={i}>
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
));
};
console.log(ref);
return (
<Grid>
<Fragment>
<div data-testid="comment-list-div" style={{ margin: "30px 0px" }}>
{props.comments.length > 2 ? (
<Fragment>
{min !== -1 && min !== -2 ? (
<Fragment>
{min !== 0 ? (
<OurSecondaryButton onClick={(e) => showComments(e)} component="span" color="secondary">
View {min !== -1 && min !== -2 ? min : 0} More Comments
</OurSecondaryButton>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : (
<OurSecondaryButton onClick={(e) => showLessComments(e)} component="span" color="secondary">
Show Less Comments
</OurSecondaryButton>
)}
</Fragment>
) : null}
</div>
</Fragment>
{showLessFlag === true ? (
// will show most recent comments below
showMoreComments()
) : (
<Fragment>
{/* filter based on first comment */}
{filterComments.map((comment, i) => (
<div key={i}>
<CommentListContainer ref={ref} comment={comment} openModal={openModal} handleCloseModal={handleCloseModal} isBold={isBold} handleClickOpen={handleClickOpen} {...props} />
</div>
))}
</Fragment>
)}
</Grid>
);
}
export default React.forwardRef(CommentList) as React.RefForwardingComponent<HTMLDivElement, any>;
I fixed it, i had to import
import CommentList from "./CommentList";
instead of
import { CommentListComponent as CommentList } from "./CommentList";
and do this to the props
ref: {
current: undefined,
},
and comment/remove this line of code from commentList
// // prevents un-necesary re renders
// // export default React.memo(CommentList);
// // will be useful for unit testing.
// export { CommentList as CommentListComponent };

Resources