I receive file url as response from api. when user clicks on download button, the file should be downloaded without opening file preview in a new tab. How to achieve this in react js?
This is not related to React. However, you can use the download attribute on the anchor <a> element to tell the browser to download the file.
<a href='/somefile.txt' download>Click to download</a>
This is not supported on all browsers: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
If you are using React Router, use this:
<Link to="/files/myfile.pdf" target="_blank" download>Download</Link>
Where /files/myfile.pdf is inside your public folder.
Triggering browser download from the frontend is not reliable.
What you should do is, create an endpoint on a server that when called, responds with the correct response headers, thus triggering the browser download.
Frontend code can only do so much. The 'download' attribute for example, might just open the file in a new tab depending on the browser and the type of the file.
The response headers you need to look at are Content-Type and Content-Disposition. You should check this answer for a more detailed explanation on those headers.