Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

How can I custom react components with TS Generics?

$
0
0

I want to create a custom component with generics. But how I do it ?

Blogs.tsx

import { useNavigation } from '@react-navigation/native';import { NativeStackScreenProps } from '@react-navigation/native-stack';import React from 'react';import { StyleSheet, Text, View, Pressable, ScrollView } from 'react-native';import Card from '../components/Card';import { IStack } from '../navigation/NavBar';import Blog from './Blog';  type NavProp = NativeStackScreenProps<IStack, 'Blogs'>const Blogs = ({ navigation }: NavProp) => {  const handleNavigate = (name: string) => {    navigation.navigate('Blog', { name });  };  return (<View><ScrollView><Blog items={['ASASD', 'asdasdsda', 'asdsda']}  onPress={(name) => console.log('PRESS')} /><Blog items={[          {            name: 'John',            age: 20          },          {            name: 'Hanna',            age: 22          }        ]}  onPress={(name) => console.log('PRESS')} /></ScrollView></View>  )};export default Blogs;

Blog.tsx

import React, { createContext, useContext, useEffect, useMemo, useReducer, useState, useRef, useDebugValue, forwardRef, useImperativeHandle } from 'react';import { Pressable, StyleSheet, Text, View, TextInput } from 'react-native';type TBlog<T> = {  items: T[],  onPress: (name: T) => void;}const Blog = <T extends { }>({ items, onPress }: TBlog<T>) => {  return (<View>        {          items.map((el, i) => (<Pressable key={i} onPress={() => onPress(el)}><Text>{el?.name ? el.name : el}</Text></Pressable>          ))        }</View>  )};export default Blog;

So if I use this component then its only for objects, but not for strings. So how can I make it for this type what I want in this blog ?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>