React - Dynamically import file path for PDF document

Initially, the page will send an http request to an API

The API will then respond with an object containing a path: ./assets/sample.pdf

I am trying to extract the urlPdf from import urlPdf from response.path

Any suggestions on how I can achieve this?

Answer №1

You might want to consider using the React PDF library for this purpose.

import React, { useState } from 'react';
import { Document, Page } from 'react-pdf';

const MyApp = () => {
  const [pageNumber, setPageNumber] = useState();
  const [numPages, setNumPages] = useState();
  const [pdfUrl, setPdfUrl] = useState();

  const handleDocumentLoadSuccess = ({ numPages }) => setNumPages(numPages);
  
  const fetchPdfPath = ({
    // implement logic to retrieve path...
    // setPdfUrl(response.data);
  })
  
  return (
    <div>
      {pdfUrl && (
        <Document
          file={pdfUrl}
          onLoadSuccess={handleDocumentLoadSuccess}
        >
          <Page pageNumber={pageNumber} />
        </Document>
      )}
      <p>Currently viewing page {pageNumber} of total {numPages}</p>
    </div>
  );
}

Answer №2

It's actually quite easy. All you need to do is use

const result = require(response.path)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Shifting the hover effect to a click event with ReactJS

Encountering an issue with hover and active states on mobile. Here is the link to my code: https://codesandbox.io/s/inspiring-wozniak-33l61?file=/src/Portfolio.scss I am attempting to change the background color of containers when tapped on mobile devices ...

What steps can be taken to ensure that when one <ListItem> component expands within a <List> component in React Material UI, all other <ListItem> components remain collapsible?

Our current application is utilizing the react material ui components for web page design. In a specific scenario, we are using the <List> material ui component, with some modifications based on our application's needs, as recommended in https:/ ...

Encountering an anomaly in persistent redux while using NEXT.JS

I recently made some updates to my ecommerce store, including adding login and register options. To ensure that user tokens are saved even after a page refresh, I decided to implement redux-persist. However, I encountered an issue where the design breaks a ...

The reducer I have is inexplicably returning undefined even though I'm certain it was added to combineReducers

After countless hours of debugging, everything seems to be in working order but the problem still persists. The main reducer file is located at reducers/index.js // @flow import { combineReducers } from "redux"; import blocks from "./blocks"; import user ...

steps to create a personalized installation button for PWA

Looking to incorporate a customized install button for my progressive web app directly on the site. I've researched various articles and attempted their solutions, which involve using beforeinstallprompt. let deferredPrompt; window.addEventListener(& ...

Utilizing TypeScript Generics to Dynamically Set Tag Names in React

I am working on a straightforward polymorphic React component that is designed to render only tag names (such as span) and not custom React components (like MyComponent). I believe this can be achieved using JSX.IntrinsicElements. Here is the code snippet ...

What steps should I take to display a Material UI grid in React without triggering the warning about the missing unique key

In my current project, I am utilizing React and Material UI to display a grid. The grid's rows are populated from an array of data, with each row containing specific information in columns structured like this: <Grid container> {myData.map((re ...

I am having trouble getting the exit animation to work in Framer Animation, despite using AnimatePresence, motion.div, and a unique key

Hello and thank you for taking the time to read this! :D I'm currently facing an issue with getting Framer Motion to work properly. My code seems to be functioning well for all features except for the exit animation. I have assigned a unique key as w ...

Inconsistent expansion panel widths observed in Chrome when using React material-ui

I've encountered an issue in Chrome where the width adjusts to fit its content instead of taking up the full width of the container. However, this problem does not occur on Firefox. https://i.stack.imgur.com/HyWGU.png When I click on the expand icon ...

What steps can be taken to reduce the size of the cards in ant.design?

Currently, I am using the ant.design Card component to present messages in a chat webapp built with react/redux. However, each card is displaying too much space around the text. Is there a way to adjust the card so that it wraps the text more closely? htt ...

What is the appropriate conversion for a CSS property name starting with -webkit when working with React?

For example, using `-webkit-text-fill-color` resulted in an error when setting it to `'red'`, stating "Using kebab-case for CSS properties in objects is not supported. Did you mean WebkitTextFillColor?" I have attempted `WebkitTextFillColor`, `w ...

Exploring the capabilities of the Next.js framework with the powerful Advanced Custom Fields Repeater

Having trouble implementing an ACF repeater field in my Next.js project. I have a block with a repeater field containing sub fields, and although I can retrieve the data, I'm unsure how to iterate through it. Below is a snippet of my JavaScript file: ...

Experiencing Problems with Routing React page on Apache2 Server

I'm encountering difficulties accessing routes other than the homepage on my React website, which is currently hosted on an Apache2 web server. You can find the page here: www.TJBrackett.com After attempting to add a .htaccess file to the directory ...

Reset input field when checkbox is deselected in React

How can I bind value={this.state.grade} to clear the input text when the checkbox is unchecked? The issue is that I am unable to modify the input field. If I were to use defaultValue, how would I go about clearing the input box? http://jsbin.com/lukewahud ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Trouble with uploading images to the server in a ReactRedux application, despite successfully sending other fields to the backend

My issue lies within the process of uploading an image file to the backend. While examining the action creator "profileAdd" through console.log(formData) originating from onSubmit() on the frontend, all fields and the image file appear to be correctly logg ...

How to make a view go fullscreen in React Native

I am attempting to create a similar animation (the pesto bruschetta) as this one. Within my listView, I have multiple cards with specific dimensions. When clicked, I want one of the cards to expand into fullscreen, displaying additional information. My c ...

Error message: 'Encountered issue with react-router-V4 and the new context API in React

Currently, I am experimenting with the integration of React Router V4 alongside the new React context API. Below is the code snippet I am working with: class App extends Component { static propTypes = { router: PropTypes.func.isRequired, ...

Steps to creating a custom text editor using React for generating blog content and storing it in a MongoDB database

I have a challenge of building a rich text editor for my web app, specifically for creating blog posts that will be saved in the database for user viewing. Initially, I planned to use a form with input fields where the title and content of the blog post w ...

Having trouble removing lines from Router Link? Unfortunately, using style={{'textDecoration': 'none'}} doesn't seem to be doing the trick

Does anyone know why the text decoration is not working on my link when I use text-decoration none? Any solutions or suggestions would be greatly appreciated. Thank you in advance! Navbar.js file import React,{useState} from "react"; import { mak ...