I am trying to make use of functional components but have trouble lifting the state. This involves a list of child MessageWithContext components inside of a parent component Chat. I don't know how many MessageWithContext there can be and they are rendered within a loop. As I understand I cannot put functional components with hooks inside of a loop since that violates rules of hooks.
The particular feature I am working on allows the user to click on a message to show context of the message like time and sender by changing the component itself.
Here's some code:
Chat.tsx:
// Get all chat related values and methods from useChat hook
const {
currentMessages, conversations, activeConversation, setActiveConversation, sendMessage, getUser, currentMessage, setCurrentMessage,
sendTyping, setCurrentUser
} = useChat();
const [detailedMessages, setDetailedMessages] = useState([false]);
{activeConversation && currentMessages.map( (g:MessageGroup) => <MessageGroup key={g.id} direction={g.direction}>
<MessageGroup.Messages>
{g.messages.map((m:ChatMessage<MessageContentType>) =>
//here I'd like to set the show detail prop based on a reference to the message
<MessageWithContext key={m.id} m={m} showDetail={detailedMessages} setShowDetail={setDetailedMessages}/>
)}
MessageWithContext:
interface IMessageWithContext {
m : ChatMessage<MessageContentType>
showDetail : boolean[]
setShowDetail : SetStateAction<any>
}
export const MessageWithContext = (props: IMessageWithContext) => {
//here I want to change the state of Chat.tsx with some kind of reference to the Message and its state
const updateShow = (show : boolean) => {
props.setShowDetail(show)
}
return (
<>
{!props.showDetail &&
<div onClick={() => updateShow(true)}>
<Message key={props.m.id} model={{
type: "html",
payload: props.m.content
}}/></div>
}
{props.showDetail &&
<div >
<Message key={props.m.id} model={{
type: "html",
payload: props.m.content
}}>
<Message.Header sender={props.m.senderId} sentTime={"just now"}>
</Message.Header>
</Message>
</div>}
</>
);
How can I make it so the updateShow function within MessageWithContext updates detailedMessages and setDetailedMessages with an array of booleans that are somehow linked to those particular MessageWithContext componets?