Skip to content

Setting Component Types Dynamically

Anastasia Mexa edited this page Nov 18, 2023 · 2 revisions

In React, component types are typically static, meaning you define the component type when you write your code. However, in some cases, you might want to conditionally render different types of components based on a dynamic value or user input. You can achieve this by using conditional rendering or dynamically selecting which component to render within your JSX.

Here's a basic example:

function App({ isButton }) {
  const Component = isButton ? 'button' : 'div';
  return <Component>{isButton ? 'Button' : 'Div'}</Component>;
}

// Usage
<App isButton={true} /> // Renders a button
<App isButton={false} /> // Renders a div

In this example, the isButton prop determines whether the component should render a button or a div. You can dynamically set the component type based on the prop or any other condition.

Clone this wiki locally