2

I'm having trouble with React's Render processing. There is a function called func1 and func2, which is called when rendering (eg: return (<func1 />)).

For example, I want to render as the actual function name from the character string at funcName in the JSON value like the following, how can I do it?

{funcName: "func1"}

If it is the above value,

I want to render as "return (<func1 />)"

Although I tried to solve this problem, even if it is used by eval or rendering it in a variable it will result in an error.

Why do you want to do this processing now is rendering with the following processing, because it is troublesome because you need to add an if statement every time you add a new function.

if (funcName.func1! = null) {
  return `<func1 />`
} else if (funcName.func2! = null) {
  return `<func2 />`
} 

An if statement is also added each time a function is added that's all.

Please answer if you know.

Udara Jayawardana
  • 1,073
  • 2
  • 14
  • 27
ReactTarou
  • 31
  • 4

2 Answers2

1

Firstly, React components name must begin with uppercase character, check this question for more details

React - User-Defined JSX Components Not rendering

Secondly instead of storing

{funcName: "Func1"}

you would store

{funcName: Func1}

and then render like

render() {
    const Func1  = obj.funcName;
    return <Func1/>
}

or if you can't replace the string with component in your data, you would do

render() {
    const Func1  = eval(obj.funcName);
    return <Func1/>
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Sorry , It is not possible to include an object type in Json data. I want to convert from string to function and rendering. However, it was not possible to render using the eval Method. – ReactTarou Apr 11 '18 at 07:10
  • Did you try `const Func1 = eval(obj.funcName); return ` – Shubham Khatri Apr 11 '18 at 07:16
  • I changed it by converting the string with eval and declaring it in uppercase letters. I discovered that it was an error because the variable was lowercase. Thank you for pointing that out.   const Func = eval (obj.funcName) return () – ReactTarou Apr 11 '18 at 07:20
  • Glad to have helped, consider accepting the answer if it helped – Shubham Khatri Apr 11 '18 at 07:21
0

Instead of putting it as element <func2 /> call the function func2()
But you func2 must return a valid react element.

Alexander Gorelik
  • 3,985
  • 6
  • 37
  • 53