Search code examples
javascripthtmlreactjsreact-hooksreact-functional-component

How to perform click in react functional component


I have a code as follows,

export const FileAttachment  = memo(({ url, title, className, ...messageBubbleProps }) => {
    const downloadFile = (link) => {
        fetch(link, {
            method: 'GET'
        })
        .then(response => response.blob())
        .then(blob => {
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = link.split('/').pop();
            document.body.appendChild(a); 
            a.click();    
            a.remove();       
        });
    }
    return (
        <MessageBubble className={createClassName(styles, 'file-attachment', {}, [className])} {...messageBubbleProps}>
            <a click="downloadFile(url)" rel='noopener noreferrer' className={createClassName(styles, 'file-attachment__inner')}>
                <FileAttachmentIcon url={url} />
                <span className={createClassName(styles, 'file-attachment__title')}>{title}</span>
                <DownloadIcon width={20} height={20} className={createClassName(styles, 'file-attachment__download-button')} />
            </a>
        </MessageBubble>
    )

});

Here when I click on anchor tag it is actually not calling the downloadFile function. Although its a react project I am not sure how can I do it. Can you please help on it. Thanks.


Solution

  • <a onClick={() => downloadFile('url')}  ... > 
      ... 
    </a>
    
    

    https://reactjs.org/docs/handling-events.html