Home >Web Front-end >JS Tutorial >How to Render Dynamic Component Names in React and JSX?

How to Render Dynamic Component Names in React and JSX?

Barbara Streisand
Barbara StreisandOriginal
2024-11-17 13:52:02308browse

How to Render Dynamic Component Names in React and JSX?

Dynamic Component Names in React and JSX

In React, dynamic component rendering allows you to create components based on their type at runtime. To illustrate this, consider the following example:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; // Returns <examplecomponent /> instead of <ExampleComponent />

An earlier solution, suggested in the React/JSX dynamic component names thread, resulted in a compilation error due to syntax differences. As an alternative, a separate method could be created for each component:

newExampleComponent() {
    return <ExampleComponent />;
}

newComponent(type) {
    return this["new" + type + "Component"]();
}

However, this approach requires a new method for each component, which can be cumbersome.

Fortunately, there is a more elegant solution that involves passing the component type as a string to the React.createElement() function. This function renders the component using the provided type. For example:

var MyComponent = Components[type + "Component"];
return <MyComponent />;

This code compiles to:

var MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});

The above is the detailed content of How to Render Dynamic Component Names in React and JSX?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn