How to call when the function you want to use for the Render of React is a string

Asked 2 years ago, Updated 2 years ago, 40 views

There is a problem with Render processing of React.
There's a function called func1 that you call when you render.(Example: return(`<func1/>`).

For example, I would like to render the following JSON value from the string in funcName as the actual function name. What should I do?

 {funcName:"func1"} 

For the above values,

`return(<func1/>)`

I want to render as

I have considered many things myself, but even if I make it into a function or render it in a variable, I get an error.

The reason why I want to do this is that I am currently rendering with the following actions, but it is troublesome because I need to add an if statement every time I add a new func.

 if(funcName.func1!=null){
return `<func1/>`
} else if(funcName.func2!=null){
return `<func2/>`
}...Add if statement every time you add a function

That's all.If you know, please reply.

javascript reactjs

2022-09-29 22:43

1 Answers

The JSX in React is the syntax sugar of React.createElement(...), so you can call React.createElement(...) directly instead of JSX.

For example, if func1 is a globally declared function,

React.createElement(window["func1"])

provides an object equivalent to <func1/>.

Note: https://reactjs.org/docs/jsx-in-depth.html


2022-09-29 22:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.