ReactJS, import files within render() -
i need import files (pdfs in case, svgs later) <embed>
element. iterating on list of props send me path pdf. when imported @ head of component, , injected works fine expected. however, need dynamically set these paths, , know cannot import inside render. using paths gives me no result.
does not work:
// pdf.src = './path/to/file.pdf' {project.projectpdfs.map((pdf, index) => <embed classname="pdf-viewer" src={pdf.src} width="100%" key={index} /> ) }
works:
import pdf './path/to/file.pdf'; {project.projectpdfs.map((pdf, index) => <embed classname="pdf-viewer" src={pdf} width="100%" key={index} /> ) }
app bootstrapped create-react-app have url-loader, not sure else going on under hood.
create-react-app using webpack
build app. url of file changed after built.
import pdf './path/to/file.pdf';
change file path hashed string , stored pdf
. have no error in second way.
in case, have 2 ways do:
import resources first
import pdf1 '/path/to/pdf1'; import pdf2 '/path/to/pdf2'; import pdf3 '/path/to/pdf3'; import pdf4 '/path/to/pdf4'; const pdfs = {pdf1, pdf2, pdf3, pdf4}; ... {project.projectpdfs.map((pdf, index) => ( <embed classname="pdf-viewer" src={pdfs[pdf]} width="100%" key={index} /> )}
dynamic import
const embeds = await promise.all(project.projectpdfs.map(async (pdf, index) => { const pdfpath = await import(pdf); return (<embed classname="pdf-viewer" src={pdfpath} width="100%" key={index} />); }));
Comments
Post a Comment