AJDee
AJDee

Reputation: 147

How can I attach word/pdf files to React Native gifted chat?

I would like to be able to send word doc/pdf files via messaging in my react native app using react native gifted chat. I have had a look at a few links which suggests using the renderActions() function in react-native-gifted-chat but it does not specify how I can implement this. Do you know how I can implement this function? Would I need to import a package like document picker or file picker in the function? If so, how can I use this? I'm fairly new to react native. Can someone please help here?

Here is what I have so far in my renderActions() method:

renderActions() {
    return(
           <Actions
           {...props}
           options={{
        ['Document']: async (props) => {
                       try {
                         const result = await DocumentPicker.pick({
                           type: [DocumentPicker.types.doc || DocumentPicker.types.docx || DocumentPicker.types.pdf],
                         });                   
                         console.log("resulting file: "+result);
                         console.log("string result? "+JSON.stringify(result));
                       } catch(e){
                           if(DocumentPicker.isCancel(e)){
                             console.log("User cancelled!")
                           } else {
                             throw e;
                          }
                        }

                       },
        ['Cancel']: (props) => {console.log("cancel")}
           }}
           icon={() => (
              <Ionicons
                  name={'add'}
                  size={28}
                  color={'#0077ff'}
                  style={{left:0, bottom:0}}
                        
              />
            )}
           onSend={args => console.log(args)}
           />
    )
    
}

Which produces:

enter image description here

enter image description here

I have managed to get the file object. Does anyone know how I can append this doc file object to the messages in gifted chat once selected? Can someone please help? How can I display in the chat box and then send the file?

Thanks.

The link https://github.com/FaridSafi/react-native-gifted-chat/issues/2111 mentions to to add parameters to the message object. For example you have this message object:

 const newMessage = {
    _id: data.send_at,
    text: data.messagetext,
    createdAt: data.send_at,
    (...),
    file_type: data?.file_type,
    file_id: data?.file_id,
 }

Then render a custom view:

 const renderCustomView = (props) => {
   if (props?.currentMessage?.file_type) {
    (...)
   }
   else {
    (...)
   }
 }

Can someone please help on where I would need to create the messages object as well as what I would need to put inside the renderCustomView function? I am really not too sure on what needs to be done.

Upvotes: 0

Views: 1922

Answers (1)

coder
coder

Reputation: 1

function renderActions(props) {
let selectFile = async () => {
  //Opening Document Picker to select one file
  try {
    const res = await DocumentPicker.pick({
      //Provide which type of file you want user to pick
      type: [DocumentPicker.types.pdf],
      //There can me more options as well
      // DocumentPicker.types.allFiles
      // DocumentPicker.types.images
      // DocumentPicker.types.plainText
      // DocumentPicker.types.audio
      // DocumentPicker.types.pdf
    });
    //Printing the log realted to the file
    console.log('res : ' + JSON.stringify(res));
    props.onSend({pdf:res.uri,file_type:'pdf'});
    //Setting the state to show single file attributes
    singleFile = res;
    // setSingleFile(res);
  } catch (err) {
    singleFile = null;
    // setSingleFile(null);
    //Handling any exception (If any)
    if (DocumentPicker.isCancel(err)) {
      //If user canceled the document selection
      alert('Canceled from single doc picker');
    } else {
      //For Unknown Error
      alert('Unknown Error: ' + JSON.stringify(err));
      throw err;
    }
  }
};
const handlePicker = () => {
  // console.log('edit');
  ImagePicker.showImagePicker({}, (response) => {
    // console.log('Response = ', response);

    if (response.didCancel) {
      console.log('User cancelled image picker');
    } else if (response.error) {
      console.log('ImagePicker Error: ', response.error);
    } else if (response.customButton) {
      console.log('User tapped custom button: ', response.customButton);
    } else {
      setAvatar({uri: response.uri});
      console.log(response.uri);
      props.onSend({image:response.uri});
    //   onSend([{"_id": "f3fda0e8-d860-46ef-ac72-0c02b8ea7ca9", "createdAt": new Date(), "image": response.uri, "user": {"_id": 1}}])
      return response.uri
      // here we can call a API to upload image on server
    }
    return avatar;
  });
};

return (
  <Actions
    {...props}
    options={{
      ['Send Image']: () => handlePicker(),
      ['Send Files']: () => selectFile(),
    }}
    icon={() => (
      <Icon name='attachment' size={28}  />
    )}
    // onSend={onSend}
  />
)}

in custom view :

export default class CustomView extends React.Component {
  
  renderPdf() {
      return (
        <TouchableOpacity style= 
            {[styles.container,this.props.containerStyle]} >
      <Image
          {...this.props.imageProps}
         style={[styles.image, this.props.imageStyle]}
         source ={{
                 uri:""
              }}
     />
    </TouchableOpacity>
    );
  }



render() {
  if (this.props.currentMessage.file_type == 'pdf') {
     return this.renderPdf();
  } else if (this.props.currentMessage.template && 
       this.props.currentMessage.template != 'none') {
     return this.renderHtml();
   }
    return null;
  }
 }

Upvotes: 0

Related Questions