Converting message react component to hooks

hello i want to use the message react component example in the docs but i am using react hooks and when i converted the code to react hooks so many things failed

please any help will be appreciated converting the component to hooks

this is my already converted component

import React, { useState, useEffect } from ‘react’;
import { f7, F7Messagebar, F7Messages, f7ready} from ‘framework7-react’;
import {
Page,
Link,
Icon,
Row,
BlockFooter,
Message,
Messagebar,
MessagebarAttachments,
MessagebarAttachment,
MessagebarSheet,
MessagebarSheetImage,
MessagesTitle,
Messages,
BlockTitle,
Col,
Button,

} from ‘framework7-react’;

const Chat = ({ }) => {
return
}

const Display = () => {
// let messages;
// let messagebar;
useEffect(()=>{
f7ready(() => {
// Init Messages
var messages = f7.messages.create({

  });

  // Init messagebar
  var messagebar = f7.messagebar.create({
    el: '.messagebar'
  });
  
});

})

  // Init Messages
   var messages = f7.messages.create({
    
  });

  var messagebar = f7.messagebar.create({
    el: 'messagebar',
  });

const router =f7.views.main.router;
const [attachments, setAttachments] = useState([])
const [sheetVisible, setSheetVisible] = useState(false)
const [typingMessage, setTypingMessage] = useState(null)
const [images, setImages] = useState([
https://cdn.framework7.io/placeholder/cats-300x300-1.jpg’,
https://cdn.framework7.io/placeholder/cats-200x300-2.jpg’,
https://cdn.framework7.io/placeholder/cats-400x300-3.jpg’,
https://cdn.framework7.io/placeholder/cats-300x150-4.jpg’,
https://cdn.framework7.io/placeholder/cats-150x300-5.jpg’,
https://cdn.framework7.io/placeholder/cats-300x300-6.jpg’,
https://cdn.framework7.io/placeholder/cats-300x300-7.jpg’,
https://cdn.framework7.io/placeholder/cats-200x300-8.jpg’,
https://cdn.framework7.io/placeholder/cats-400x300-9.jpg’,
https://cdn.framework7.io/placeholder/cats-300x150-10.jpg’,
])
const [responseInProgress, setResponseInProgress] = useState(false)

const [answers, setAnswers] = useState([
‘Yes!’,
‘No’,
‘Hm…’,
‘I am not sure’,
‘And what about you?’,
‘May be ;)’,
‘Lorem ipsum dolor sit amet, consectetur’,
‘What?’,
‘Are you sure?’,
‘Of course’,
‘Need to think about it’,
‘Amazing!!!’,
])

const [people, setPeople] = useState([
{
name: ‘Kate Johnson’,
avatar: ‘https://cdn.framework7.io/placeholder/people-100x100-9.jpg’,
},
{
name: ‘Blue Ninja’,
avatar: ‘https://cdn.framework7.io/placeholder/people-100x100-7.jpg’,
},
])

const [messagesData, setMessagesData] = useState([
{
type: ‘sent’,
text: ‘Hi, Kate’,
},
{
type: ‘sent’,
text: ‘How are you?’,
},
{
name: ‘Kate’,
type: ‘received’,
text: ‘Hi, I am good!’,
avatar: ‘https://cdn.framework7.io/placeholder/people-100x100-9.jpg’,
},
{
name: ‘Blue Ninja’,
type: ‘received’,
text: ‘Hi there, I am also fine, thanks! And how are you?’,
avatar: ‘https://cdn.framework7.io/placeholder/people-100x100-7.jpg’,
},
{
type: ‘sent’,
text: ‘Hey, Blue Ninja! Glad to see you ;)’,
},
{
type: ‘sent’,
text: ‘Hey, look, cutest kitten ever!’,
},
{
type: ‘sent’,
image: ‘https://cdn.framework7.io/placeholder/cats-200x260-4.jpg’,

},
{
  name: 'Kate',
  type: 'received',
  text: 'Nice!',
  avatar: 'https://cdn.framework7.io/placeholder/people-100x100-9.jpg',
},
{
  name: 'Kate',
  type: 'received',
  text: 'Like it very much!',
  avatar: 'https://cdn.framework7.io/placeholder/people-100x100-9.jpg',
},
{
  name: 'Blue Ninja',
  type: 'received',
  text: 'Awesome!',
  avatar: 'https://cdn.framework7.io/placeholder/people-100x100-7.jpg',
},

])

function attachmentsVisible() {
return attachments.length > 0;
}

function placeholder() {
return attachments.length > 0 ? ‘Add comment or Send’ : ‘Message’;
}

function isFirstMessage(message, index) {
const previousMessage = messagesData[index - 1];
if (message.isTitle) return false;
if (!previousMessage || previousMessage.type !== message.type || previousMessage.name !== message.name) return true;
return false;
}

function isLastMessage(message, index) {
const nextMessage = messagesData[index + 1];
if (message.isTitle) return false;
if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name) return true;
return false;
}

function isTailMessage(message, index) {
const nextMessage = messagesData[index + 1];
if (message.isTitle) return false;
if (!nextMessage || nextMessage.type !== message.type || nextMessage.name !== message.name) return true;
return false;
}

function deleteAttachment(image) {
const attachments = attachments;
const index = attachments.indexOf(image);
attachments.splice(index, 1);
setAttachments(attachments);
}

function handleAttachment(e) {
const attachments = attachments;
const index = (e.target).parents(‘label.checkbox’).index();
const image = images[index];
if (e.target.checked) {
// Add to attachments
attachments.unshift(image);
} else {
// Remove from attachments
attachments.splice(attachments.indexOf(image), 1);
}
setAttachments(attachments);
}

function sendMessage() {
const text = messagebar.getValue().replace(/\n/g, ‘
’).trim();
const messagesToSend = [];
attachments.forEach((attachment) => {
messagesToSend.push({
image: attachment,
});
});
if (text.trim().length) {
messagesToSend.push({
text,
});
}
if (messagesToSend.length === 0) {
return;
}

// Reset attachments
setAttachments([]);

// Hide sheet
setSheetVisible(false);

// Send message
setMessagesData([...messagesData, ...messagesToSend])

messagebar.clear();

// Focus area
if (text.length) messagebar.focus();

// Mock response
if (responseInProgress) return;
setResponseInProgress(true);

setTimeout(() => {
  const answer = answers[Math.floor(Math.random() * answers.length)];
  const person = people[Math.floor(Math.random() * people.length)];

  setTypingMessage({
    name: person.name,
    avatar: person.avatar,
  })
 
  setTimeout(() => {
    setMessagesData([...messagesData, {
      text: answer,
      type: 'received',
      name: person.name,
      avatar: person.avatar,
    }]);

    setTypingMessage(null);

    setResponseInProgress(false);
   
  }, 4000);
}, 1000);

}

function ShowModal() {
dialog.open()
}

function Click(){
// router.back();
console.log(messages)
}

return (

<div style={{textAlign:“center”,padding:“0 7%”,marginTop:“20px”}}>

<Col width=“20” style={{textAlign:“left”}} id=“auto”>




<Col width=“60” style={{textAlign:“center”}} id=“auto”>
<h2 style={{fontSize:“20px”}}>
Chat


<Col width=“20” style={{textAlign:“right”}} id=“auto”>


    <div style={{marginTop:"10%",marginBottom:"13%",textAlign:"left"}}>    
      <Row noGap>
        <Col width="15"  id="auto" className="center">
        <img src="static/chef2.jpg" alt="chopper_img" id="user_img"/>
        </Col>
        <Col width="45"  id="auto" className="left">
          <BlockTitle style={{marginBottom:"0",marginLeft:"0"}}>Bello Abdul</BlockTitle>
          <BlockFooter style={{marginTop:"0",padding:"0"}}>chopper</BlockFooter>
        </Col>
        <Col width="10"  id="auto" className="right">
          
        </Col>
        <Col width="30"  id="auto" style={{textAlign:"right"}}>
          <Link iconOnly>
            <Icon ios="f7:phone_circle_fill" aurora="f7:phone_circle_fill" md="material: phone_circle_fill" color="#ed404a"></Icon>
          </Link>
        </Col>
        <Col width="100" style={{marginTop:"-7%"}}><hr style={{borderColor:"#f4f4f8"}}/>
        <Messagebar
          placeholder={placeholder}
          ref={(el) => {messagebar = el}}
          init={true}
          className="messagebar"
          attachmentsVisible={attachmentsVisible}
          sheetVisible={sheetVisible}
        >
        <Link
          iconIos="f7:camera_fill"
          iconAurora="f7:camera_fill"
          iconMd="material:camera_alt"
          slot="inner-start"
          onClick={() => {setSheetVisible(!sheetVisible)}}
        ></Link>
        <Link
          iconIos="f7:arrow_up_circle_fill"
          iconAurora="f7:arrow_up_circle_fill"
          iconMd="material:send"
          slot="inner-end"
          onClick={sendMessage}
        ></Link>
        <MessagebarAttachments>
          {attachments.map((image, index) => (
            <MessagebarAttachment
              key={index}
              image={image}
              onAttachmentDelete={() => deleteAttachment(image)}
            ></MessagebarAttachment>
          ))}
        </MessagebarAttachments>
        <MessagebarSheet>
          {images.map((image, index) => (
            <MessagebarSheetImage
              key={index}
              image={image}
              checked={attachments.indexOf(image) >= 0}
              onChange={handleAttachment}
            ></MessagebarSheetImage>
          ))}
        </MessagebarSheet>
    </Messagebar>

    <Messages ref={(el) => {messages = el}}>
      <MessagesTitle><b>Sunday, Feb 9,</b> 12:58</MessagesTitle>

      {messagesData.map((message, index) => (
        <Message
          key={index}
          type={message.type}
          image={message.image}
          name={message.name}
          avatar={message.avatar}
          first={isFirstMessage(message, index)}
          last={isLastMessage(message, index)}
          tail={isTailMessage(message, index)}
        >
          {message.text && (
            <span slot="text" dangerouslySetInnerHTML={{__html: message.text}} />
          )}
        </Message>
      ))}
      {typingMessage && (
        <Message
          type="received"
          typing={true}
          first={true}
          last={true}
          tail={true}
          header={`${typingMessage.name} is typing`}
          avatar={typingMessage.avatar}
        ></Message>
      )}
    </Messages>
       
        </Col>
 
      </Row>
    </div>
  </div>
) } export default Chat;

here you have;


i did it bcs im learning react. Im pretty new, so dont take my code for granted. There is a high chance that i did something wrong. Or there was a better way to do it.

2 Likes

@pvtallulah thanks alot :pray: :handshake: but still having some issues with selecting images in attachment … i get an error as below

const index =
$$(e.target)
.parents(“label.checkbox”)
.index();

but i removed the two dollar sign ($$) to look like the code below

e.target
      .parents("label.checkbox")
      .index();

but i now get an error saying e.target.parents is not a function