1

I have a module JS where i use React

 import React from 'react'

My component

export default class TaskDetail extends Component {...

I have a a string that represents a code:

str=`props => {
  return React.createElement(.....

and I would use this code in a module JS like this:

const MyCustomWidget = eval(str)

so that one it would be equal to write:

const MyCustomWidget = props => {
  return React.createElement(.....

I use MyCustomWidget to create a custom element in react-jsonschema-form

the point of my question is: in my module i have imported React but i have error React is not defined that is because the result of eval have another scope... if i write on top of my module:

 window.React = React

it works! but I wouldn't want to use

It is possible use eval and use the scope of my module ? I would like to use my imported React variable in my module without use window.React=React

is possible?

Angelotti
  • 673
  • 1
  • 6
  • 20
  • Take a look here, it might help! https://stackoverflow.com/questions/9781285/specify-scope-for-eval-in-javascript – MKougiouris Jan 04 '19 at 16:14
  • 3
    Just because something is possible, does not mean you should do it. Find another pattern that does not use eval. – Dimitar Christoff Jan 04 '19 at 16:16
  • Eval should really be avoided if possible, but this should be possible: https://stackoverflow.com/a/43306962/3893820 – dan Jan 04 '19 at 16:17
  • Well, theoretically, but I wouldn't recommend it, just use `new Function( React, `return ${str}` )( React );`. Then React would be passed as a function parameter which would be available for your code internally. I don't know if anything else would go wrong though – Icepickle Jan 04 '19 at 16:18
  • Can't you create a local variable that is a function that returns the function you want? You can pass arguments to the outer function that can be used when the inner function executes. I really feel like `eval` is a bad solution here. – Greg Burghardt Jan 04 '19 at 16:33
  • i recived the string str from the backend – Angelotti Jan 04 '19 at 16:37

1 Answers1

0

If you want to experiment with it...

const evalInContext = a =>
    // eslint-disable-next-line no-new-func
    new Function('require', 'const React = require("react");' + a).bind(
        null,
        require
    );

See how they evaluate and run react code from a live editor in react-styleguidist https://github.com/styleguidist/react-styleguidist/blob/34f3c83e76/src/client/rsg-components/ReactExample/ReactExample.spec.js

Once again, if you cannot 100% trust what you eval, don't do it.

Dimitar Christoff
  • 26,147
  • 8
  • 50
  • 69