question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

React string eval doesn't seem to work

See original GitHub issue

Describe the bug I’m trying to run some react code from a string downloaded from a remote source but I keep getting the following error “TypeError: Constructor Text requires ‘new’”. In a standard create-react-app environment this works fine.

import React from 'react';

const Test = () => {
  const react = React;
  return eval("react.createElement('p', null, 'Testing');")
}

function App() {  
  return (
    <div className="App">
      <Test />
    </div>
  );
}

export default App;

But in react-pdf the equivalent code throws an error.

import React from 'react';
import { PDFViewer, Document, Page, Text } from '@react-pdf/renderer';

const Test = () => {
  const react = React;
  return eval("react.createElement(Text, null, 'Testing');");
}

function App() {
  return (
    <PDFViewer>
      <Document>
        <Page>
          <Test />
        </Page>
      </Document>
    </PDFViewer>
  );
}

export default App;

Why Do This? Just for background, I have some html rich text(i.e. <p>This is an <strong>example</strong> string</p>) I want to render in my react-pdf document. Since this content is dynamic I can’t just rebuild the styling in react-pdf. I don’t believe there is any out of the box way to display html rich text. I am playing with the idea of implementing the html elements in react pdf and just having react-pdf render them.

In a nut shell doing something like this should get me what I need if eval worked as expected.

import React from 'react';
import { PDFViewer, Document, Page, Text } from '@react-pdf/renderer';
import { P, Strong } from './primitives';  // I have replicated all the components I need to use

// Component displays react-pdf interpretation of HTML string
const Test = () => {
  const react = React;
  // This is an mock of what I would get back in my api response
  const htmlString = '<p>This is an <strong>example</strong> string</p>`
  const modifiedHtmlString = htmlString.replace(/(<[a-z]|<\/[a-z])+/g, txt => txt.toLocaleUpperCase());
  return eval(Babel.translate(modifiedHtmlString, { presets: ["react"] }).code));
}

This is what I have come up with so far for displaying dynamic html rich text content in react-pdf but I’m open to other approaches if a better one exists.

To Reproduce Steps to reproduce the behavior including code snippet (if applies):

  1. running this code works fine react.createElement(Text, null, 'Testing');
  2. running this code throws an error eval("react.createElement(Text, null, 'Testing');");

Expected behavior I expected that I would be able to eval react code with react-pdf in the same way I could with standard react-dom.

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Firefox
  • React-pdf version [e.g. v1.6.4]

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:5 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
dberringercommented, Sep 29, 2019

@asgerhallas That’s really cool. I have not messed with acorn before. I don’t see any reason why this won’t work. I’m still curious if @diegomura knows why eval doesn’t work normally in react-pdf but I think this will work around my problem. Thanks!!!

0reactions
diegomuracommented, Oct 5, 2019

I looked at this and couldn’t figure out why it does not work like that. It’s an edge case though, and it would be better to follow an approach such as the one proposed by @asgerhallas . I’m closing this issue since it’s not something we should encourage to do

Read more comments on GitHub >

github_iconTop Results From Across the Web

Having trouble with eval() with React, it won't actually evaluate ...
Apologies, i should specify that expression is based on an array of values created by clicking buttons with 0-9 and the 4 basic...
Read more >
eval() - JavaScript - MDN Web Docs - Mozilla
The eval() function evaluates JavaScript code represented as a string and returns its completion value. The source is parsed as a script.
Read more >
Evaluating JavaScript code via eval() and new Function() - 2ality
This blog post examines how one can dynamically evaluate code in JavaScript. eval(). eval(str) evaluates the JavaScript code in str.
Read more >
Everything Wrong With JavaScript `eval()`
The main reason you should avoid using it is a security. Evaluating JavaScript code from a string is hazardous. A string may consist...
Read more >
JSX in React – Explained with Examples - freeCodeCamp
This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code. This is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found