forked from academind/react-complete-guide-course-resources
-
Notifications
You must be signed in to change notification settings - Fork 0
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.
- Home
- Creating a React project
- Compilation and execution process
- Components & File Extensions
- React Basics
- Examples (Components and States)
- Using Fragments
- Setting Default Prop Values
- Fowarding Props
- Working with Multiple JSX Slots
- Setting Component Types Dynamically
- Updating state based on previous state value
- JavaScript Data Types and Memory Storage
- StrictMode Component
- Using Ref
- Forwarding Refs
- Context-API
- useReducer
- Side Effects
- Memoization
- Functional vs Class‐Based Components
- Performing HTTP requests
- Custom Hooks
- Form Submission and Validation
- Redux
- Router
- Lazy-Loading
- TanStack Query
- Next.js
- TypeSript