Ways to dynamically display components in React Native

In my React Native app, I have a custom tab control that is rendered dynamically using the following configuration:

const TABS = [
   { title: 'Tab 1', component: MyComponentOne },
   { title: 'Tab 2', component: MyComponentTwo }
];

The title property is used for the tab title, and when a tab is selected, I want to render the corresponding component inside an Animated.FlatList.

Is there a way for me to dynamically render MyComponentOne and MyComponentTwo, instead of having to do this manually?:

if (typeof item.component === 'MyComponentOne') return <MyComponentOne />
if (typeof item.component === 'MyComponentTwo') return <MyComponentTwo />

Any suggestions on how to achieve this?

Answer №1

If you want to display different components based on tab titles, you can create an object mapping each tab title to its corresponding component. Then, you can render the desired component by referencing the title in that object.

const tabs: Record<string, React.ReactNode> = {
  "Tab 1": <MyComponent/>,
  "Tab 2": <MyOtherComponent/>
}

Below is a functional example written in JavaScript. You just need to add types for it to work properly.

const tabs = {
  "Tab 1": <MyComponent/>,
  "Tab 2": <MyOtherComponent/>,
  "Tab 3": <YetAnotherComponent/>
}

function MyComponent(){
  return (
      <div class="component my">
        MyComponent
      </div>
  )
}

function MyOtherComponent(){
  return (
      <div class="component other">
        MyOtherComponent
      </div>
  )
}

function YetAnotherComponent(){
  return (
      <div class="component yetanother">
        YetAnotherComponent
      </div>
  )
}

function TabComponent(){
  const [activeTab, setActiveTab] = React.useState("Tab 1");

  return (
      <div class="tabcomponent">
        <div class="tabs">
            <button class="tab" onClick={() => setActiveTab("Tab 1")}>
              Tab 1
            </button>
            <button class="tab" onClick={() => setActiveTab("Tab 2")}>
              Tab 2
            </button>
            <button class="tab" onClick={() => setActiveTab("Tab 3")}>
              Tab 3
            </button>
        </div>
          {tabs[activeTab]}
      </div>
  );
}
ReactDOM.render(<TabComponent/>, document.getElementById('root'));
.tabcomponent {
  border: 1px solid black;
}

.tabs {
  display: flex;
  flex-grow: 1;
}

.tab {
  flex-grow: 1;
  flex-basis: 100%;
}

.component {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.my {
  background-color: red;
}

.other {
  background-color: yellow;
}

.yetanother {
  background-color: green;
}
<script crossorigin src="https://unpkg.com/react@18/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlocking the potential of nested conditional types in TypeScript

The source of the autogenerated type below stems from a GraphQL query: export type OfferQuery = { __typename?: 'Query' } & { offer: Types.Maybe< { __typename?: 'Offer' } & Pick<Types.Offer, 'id' | 'nam ...

Creating an Angular form group that includes dynamic form controls with custom form control names

Seeking to implement a formGroup that dynamically adjusts based on JSON data like this: const LIMITS: Limit[] = [ { id: 'limit1', value: 1000, disabled: false }, { id: 'limit2', value: 500, disabled: tru ...

The production build for Angular 9 Keyvalues pipe fails to compile

After successfully running my app on the development server with ng serve, I encountered a failure when trying to build it for production. The error message that popped up was: ERROR in src/app/leaderboard/leaderboard.component.html(9,17): Argument of typ ...

Tips for creating a sequelize transaction in TypeScript

I am currently working with sequelize, node js, and TypeScript. I am looking to convert the following command into TypeScript. return sequelize.transaction().then(function (t) { return User.create({ firstName: 'Homer', lastName: ' ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

An error occured: Unable to access the 'taxTypeId' property since it is undefined. This issue is found in the code of the View_FullEditTaxComponent_0, specifically in the update

I am encountering an issue with a details form that is supposed to load the details of a selected record from a List Form. Although the details are displayed correctly, there is an error displayed on the console which ultimately crashes the application. T ...

A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this: <div class="container"> <div class="row my-4"> <div class="col-md-12 d-flex justify-content-center"> <h2> ...

Determining the exact position of an image with resizeMode set to 'contain' in React Native

I am currently developing an object detection app using React Native. The process involves sending an image to the Google Vision API, which then returns a JSON file containing coordinates and sizes of objects detected within the image. My goal is to draw r ...

Exploring how enums can be utilized to store categories in Angular applications

My application has enums for category names on both the back- and front-end: export enum CategoryEnum { All = 'All', Category1 = 'Category1', Category2 = 'Category2', Category3 = 'Category3', Cate ...

"Unable to convert object into a primitive value" error message appears on Internet Explorer

Currently working on a webpage using Angular 7. The code is functioning perfectly in Chrome, however, I am facing an Exception error while running it in IE: An issue arises: Can't convert object to primitive value (polyfills.ts) The source of the er ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Sluggish website loading time

Hey there, I'm currently developing a website and I'm facing a major issue with one of my pages loading slowly and experiencing lag. I'm unsure if this is due to the on scroll listeners or the excessive references in my code. Could it possib ...

Obtaining Navigation Parameters within Custom React Navigation Title

In the React Navigation StackNavigator, I created a custom title that looks like this: const CustomStackNavigator = StackNavigator({ Home: { screen: HomeScreen } }, { navigationOptions: { headerTitle: <GradientHeader title={this.props.nav ...

After updating the state in a Reducer with Redux Toolkit, make sure to utilize a

Issue: Seeking efficient code writing methods. Here is a detailed example of my Redux Toolkit slice below: import { createSlice } from '@reduxjs/toolkit'; import { setCookie } from '../../utils/storageHandler'; const initialState = { ...

What is the best way to declare a TypeScript type with a repetitive structure?

My data type is structured in the following format: type Location=`${number},${number};${number},${number};...` I am wondering if there is a utility type similar to Repeat<T> that can simplify this for me. For example, could I achieve the same resul ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...

An issue occurred while trying to run Ionic serve: [ng] Oops! The Angular Compiler is in need of TypeScript version greater than or equal to 4.4.2 and less than 4.5.0, but it seems that version 4

Issue with running the ionic serve command [ng] Error: The Angular Compiler requires TypeScript >=4.4.2 and <4.5.0 but 4.5.2 was found instead. Attempted to downgrade typescript using: npm install typescript@">=4.4.2 <4.5.0" --save-dev --save- ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

Sharing information between different pages in NEXT.js version 14

After performing a fetch and receiving a successful response containing data as an object, I use router.push to redirect the page to another one where I want to display the fetched data. const handleSubmit = async (event: any) => { event.preventDefa ...

What is the best method to invoke a function from the header in react-navigation?

I'm currently using react navigation at https://reactnavigation.org/. Within my Component, I have a method: class Sing extends Component { singASong = () => { console.log('hello i am singing'); } } This Component will be rend ...