I have a set of pdf files sitting in a folder in my project.
All I need to do is to create a link to these PDF files and view them in browser or download it.
I use React Router 4 and React 16 and create-react-app bootstrapping tool.
Regardless of how I link it (Link component or a tag) it still goes to my last Route in my router config.
I have been googling for last two hours... But no luck..
Is there any way to tell router not to route for PDF/XLS files?
Thanks
I met the same issue, I think it's because of the way CRA handles queries : I ended up putting my PDF files in the public folder, and link to them using :
{process.env.PUBLIC_URL + '/myfile.pdf'}
as src to my tags.
Not the best way I guess, but works fine enough...
I tried squizz's way, but the problem I'm finding is that if you click the link more than once or twice, it will revert to going back to going to the last route.
You can make a folder in src
to hold your pdf's, and link to them normally, ex:
import pdf from '../files/myfile.pdf'
render () {
<a href={pdf}>Click here for my pdf</a>
}
The only problem is, you will get a hash appended to your file, so it will come out as myfile.d2e24234.pdf or something. I think it has to do with file-loader...currently trying to figure it out.
EDIT
The answer if you don't want to use src is to delete the service worker from the create-react-app project. For some reason it affects react-router's handling of server routes.
I made a github issue here to read about it: https://github.com/facebookincubator/create-react-app/issues/3608
Ran into this same issue and fixed it by resorting to old-fashioned html:
<a href="docs/document.pdf">
Document
</a>
And copying the pdf to my publicly served folder with CopyWebpackPlugin in webpack.config:
plugins: [
new CopyWebpackPlugin([
{
from: 'docs/document.pdf',
to: path.resolve(BUILD_PATH + "/docs/document.pdf")
},
])
]
This worked for me:
<Link
to="route"
onClick={(event) => { event.preventDefault(); window.open(filePath); }}>
Click to download
</Link>