1
- import React , { useState } from 'react' ;
2
- import { Accordion , ListGroup , ListGroupItem , Form , Button } from 'react-bootstrap' ;
1
+ import React , { useState , useRef , useEffect } from 'react' ;
2
+ import { Accordion , ListGroup , ListGroupItem , Form , Button , Badge } from 'react-bootstrap' ;
3
3
4
4
const Chat = ( { currentUser, messages, sendMessage } ) => {
5
5
const [ text , setText ] = useState ( '' ) ;
6
+ const chatContainerRef = useRef ( null ) ;
7
+ const [ isAccordionOpen , setIsAccordionOpen ] = useState ( true ) ;
6
8
7
9
const handleSend = ( ) => {
8
10
console . log ( "I am sending" )
@@ -12,13 +14,27 @@ const Chat = ({ currentUser, messages, sendMessage }) => {
12
14
}
13
15
} ;
14
16
17
+ useEffect ( ( ) => {
18
+ if ( chatContainerRef . current ) {
19
+ chatContainerRef . current . scrollTop = chatContainerRef . current . scrollHeight ;
20
+ }
21
+ } , [ messages ] ) ;
22
+
15
23
return (
16
- < Accordion defaultActiveKey = "0" className = 'mt-3' >
17
- < Accordion . Item eventKey = "0" >
18
- < Accordion . Header >
19
- Chat
20
- </ Accordion . Header >
21
- < Accordion . Body className = "scrollable-accordion-body" >
24
+ < Accordion defaultActiveKey = "0" className = 'mt-3' onSelect = { ( eventKey ) => setIsAccordionOpen ( eventKey === "0" ) } >
25
+ < Accordion . Item eventKey = "0" >
26
+ < Accordion . Header >
27
+ Chat
28
+ </ Accordion . Header >
29
+ < Accordion . Body >
30
+ < div
31
+ ref = { chatContainerRef }
32
+ style = { {
33
+ maxHeight : '300px' ,
34
+ overflowY : 'auto' ,
35
+ marginBottom : '1rem' ,
36
+ } }
37
+ >
22
38
< ListGroup >
23
39
{ messages . map ( ( msg , idx ) => (
24
40
< ListGroupItem
@@ -28,11 +44,13 @@ const Chat = ({ currentUser, messages, sendMessage }) => {
28
44
textAlign : msg . sender === currentUser ? "right" : "left"
29
45
} }
30
46
>
31
- { msg . text }
47
+ < Badge bg = "secondary" > { msg . sender } </ Badge > : { msg . text }
32
48
</ ListGroupItem >
33
49
) ) }
34
50
</ ListGroup >
35
- < Form className = "mt-3" onSubmit = { ( e ) => { e . preventDefault ( ) ; handleSend ( ) ; } } >
51
+ </ div >
52
+ { isAccordionOpen && ( // Only show message input when accordion is open
53
+ < Form onSubmit = { ( e ) => { e . preventDefault ( ) ; handleSend ( ) ; } } >
36
54
< Form . Group controlId = "messageInput" >
37
55
< Form . Control
38
56
type = "text"
@@ -45,8 +63,9 @@ const Chat = ({ currentUser, messages, sendMessage }) => {
45
63
Send
46
64
</ Button >
47
65
</ Form >
48
- </ Accordion . Body >
49
- </ Accordion . Item >
66
+ ) }
67
+ </ Accordion . Body >
68
+ </ Accordion . Item >
50
69
</ Accordion >
51
70
) ;
52
71
} ;
0 commit comments