Home > Web Front-end > JS Tutorial > How to Dynamically Render Components in React/JSX?

How to Dynamically Render Components in React/JSX?

Mary-Kate Olsen
Release: 2024-11-15 14:12:02
Original
481 people have browsed it

How to Dynamically Render Components in React/JSX?

Dynamic Component Rendering in React/JSX

React's JSX allows for declarative component rendering, but sometimes developers may need to dynamically render components based on their type.

The Issue

When attempting to render a component dynamically using the code snippet below, an error occurs:

var type = "Example";
var ComponentName = type + "Component";
return <ComponentName />; // Error: expected XML, got array
Copy after login

The error arises because the code uses array syntax while the JSX expects XML. Other solutions, such as creating a method for each component, are not elegant.

The Solution

The React documentation now provides an official solution for dynamic component rendering:

const MyComponent = Components[type + "Component"];
return <MyComponent />;
Copy after login

This code compiles to:

const MyComponent = Components[type + "Component"];
return React.createElement(MyComponent, {});
Copy after login

The variable MyComponent stores the component class and is capitalized. The React.createElement function then uses this class to create the component element.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template