react native measure is undefined - scrollview

I have a ScrollView in which there is several View lick so
<ScrollView>
<View
ref = {"view1"}
style = {{
height: 200,
backgroundColor: "#FF0000"
}}
>
<Text>{"text 1"}</Text>
</View>
<View
ref = {"view2"}
style = {{
height: 200,
backgroundColor: "#FF0000"
}}
>
<Text>{"text2"}</Text>
</View>
</ScrollView>
higher I have a 2 button when press start this code
// buttonPress is either "view1" || "view2"
this.refs[buttonPress].measure((fx, fy, width, height, px, py) => {
console.log("Fy", fy);
console.log("Py", py);
});
but I get en err saying that measure is undefined and indeed I can get the ref correctly I made sure of that but when I printed all the key inside the object here what come out :
11:38:28.404 I 'KEY', 'props'
11:38:28.404 I 'KEY', 'context'
11:38:28.404 I 'KEY', 'refs'
11:38:28.405 I 'KEY', 'updater'
11:38:28.405 I 'KEY', 'setWrappedInstance'
11:38:28.405 I 'KEY', 'resolveConnectedComponentStyle'
11:38:28.405 I 'KEY', 'state'
11:38:28.405 I 'KEY', '_reactInternalFiber'
11:38:28.405 I 'KEY', '_reactInternalInstance'
11:38:28.405 I 'KEY', '__reactInternalMemoizedUnmaskedChildContext'
11:38:28.405 I 'KEY', '__reactInternalMemoizedMaskedChildContext'
11:38:28.405 I 'KEY', '__reactInternalMemoizedMergedChildContext'
11:38:28.405 I 'KEY', '_root'
11:38:28.406 I 'KEY', 'wrappedInstance'
11:38:28.406 I 'KEY', 'isReactComponent'
11:38:28.406 I 'KEY', 'setState'
11:38:28.406 I 'KEY', 'forceUpdate'
as you can see measure is no were to be found (i know it is, not the best way of finding what is inside an object but it should a least be mentioned somewhere publicly for people to use, no?

You are not referencing your view properly. That's not how to pass ref prop to a view. Though there is a new API for doing that. The old way is using callback.
This is what your code should look like:
Import React, {createRef} from 'react';
import {ScrollView, View} from 'react-native';
const firstView = createRef(null);
const secondView = null
<ScrollView>
<View
ref = {firstView}
style = {{
height: 200,
backgroundColor: "#FF0000"
}}
>
<Text>{"text 1"}</Text>
</View>
<View
ref = {view => secondView = view}
style = {{
height: 200,
backgroundColor: "#FF0000"
}}
>
<Text>{"text2"}</Text>
</View>
Then later in your handles, you can access the two view using something like these:
// first view is using the new API
firstView.current.measure((x, y, width, height, pagex, pagey) => {
console.log('x coordiante: ', pagex);
console.log('y coordinate: ', pagey);
});
// secondView is using the old API
secondView.measure((x, y, width, height, pagex, pagey) => {
console.log('x coordiante: ', pagex);
console.log('y coordinate: ', pagey);
});

Related

mobile app want graphical text to change font size per line automatically, like on tiktok/instagram alternating lines different sizes

On TikTok and Instagram, they can generate automatically text font size like this image, where alternating lines have different font sizes automatically. I'm trying to figure out how to code that in React Native for mobile IOS and Android: [[enter image description here](https://i.stack.imgur.com/vkhIo.jpg)](https://i.stack.imgur.com/XcjLq.jpg)
I couldn't figure it out. I made something that I'm not crazy about, which is just having a larger font on the first three lines and then a smaller font. See image: But I don't like it. enter image description here
I totally misunderstood what PixelRatio.getFontScale did. I thought it would provide the average width a single character takes up on screen. If you can find a way to get a rough estimate of the width of a single character, then this method will work link:
import { useEffect, useState } from 'react';
import { View, StyleSheet, Text, PixelRatio } from 'react-native';
import rnTextSize from 'react-native-text-size';
import reduce from 'awaity/reduce';
import useViewLayout from './useViewLayout';
const fontScale = PixelRatio.getFontScale();
const showLayoutValues = true
export default function MultiLineText({
width,
containerStyle,
textStyle1 = { fontSize: 16 },
textStyle2 = { fontSize: 22 },
str,
...textProps
}) {
// containerLayout will provide the max width each line can have
const [containerLayout, onContainerLayout] = useViewLayout();
// lines was created in a useMemo hook but I wasnt sure if
// useMemo could handle async
const [lines, setLines] = useState([]);
useEffect(() => {
const calcLines = async () => {
let words = str.split(' ').filter((s) => s.trim().length);
let newLines = await words.reduce(
async (prevPromise, curr, index) => {
const prev = await prevPromise;
let lineIndex = prev.length - 1;
let style = index % 2 == 0 ? textStyle1 : textStyle2;
const fontSize = style.fontSize;
// I wanted to use this https://github.com/aMarCruz/react-native-text-size/
// to measure text width but expo doesnt support it
const config = {
// if you exported from expo and link rnTextSize set this to true
useMeasureModule:false,
fontProps:style
}
const useMeasureModule = false;
let lineWidth = await getTextWidth(
prev[lineIndex],
fontSize,
config
);
let wordWidth = await getTextWidth(curr, fontSize, config);
// if currentLine can fit the next word add it
if (lineWidth + wordWidth < (width || containerLayout.width))
prev[lineIndex] += curr + ' ';
// or put it on the next line
else {
prev[lineIndex + 1] = curr + ' ';
}
return prev;
},
['']
);
setLines(newLines);
};
calcLines();
}, [str, containerLayout, width, textStyle1, textStyle2]);
return (
<>
{showLayoutValues && <Text>Container Layout: {JSON.stringify(containerLayout,null,4)}</Text>}
<View
style={[styles.container, containerStyle]}
onLayout={onContainerLayout}>
{lines.map((line, i) => (
<Text
{...textProps}
// to ensure that lines dont wrap
numberOfLines={1}
style={[textProps.style, i % 2 == 0 ? textStyle1 : textStyle2]}>
{line}
</Text>
))}
</View>
</>
);
}
const getTextWidth = async (str, fontSize, config={}) => {
const {fontProps, useMeasureModule} = config;
if (!useMeasureModule) {
// random mathing
return str.length * fontScale * fontSize ** 0.8;
}
let measure = await rnTextSize.measure({
...fontProps,
text: str,
});
return measure.width;
};
const styles = StyleSheet.create({
container: {
width: '100%',
},
});
And then in use:
export default function App() {
return (
<View style={styles.container}>
<MultiLineText
containerStyle={{
width: '100%',
backgroundColor: '#eef',
alignSelf: 'center',
alignItems: 'center',
}}
textStyle1={styles.text}
textStyle2={styles.text2}
str="I am really not sure as of how long this text needs to be to exceed at least 3 lines. I could copy and paste some stuff here but I think if I just type and type it would be quicker than googling, copying, and pasting"
/>
</View>
);
}
I just found out that onTextLayout is a thing. It gives about each line in the Text component, including info about the characters present on each line. This could be used to figure out where to break lines of text (no planned web support):
After tying the str prop to a text input it became very clear that it is ideal to prevent this component from re-rendering as much as possible so I made additional changes (demo)
import { useState, useCallback, useEffect, memo } from 'react';
import { View, StyleSheet, Text, ScrollView } from 'react-native';
// text lines will alternate between these styles
const defaultLineStyles = [
{ color: 'red', fontSize: 16 },
{ color: 'blue', fontSize: 22 },
{ color: 'green', fontSize: 28 },
];
function MultiLineText({
containerStyle,
lineStyles = defaultLineStyles,
str,
...textProps
}) {
const [lines, setLines] = useState([]);
// each time a substring is added to line,
// remove the substring from remainingStr
const [remainingStr, setRemainingStr] = useState('');
const onTextLayout = useCallback((e) => {
// the first line of text will have the proper styling
let newLine = e.nativeEvent.lines[0].text;
setLines((prev) => {
return [...prev, newLine];
});
// remove newLine from remainingStr
setRemainingStr((prev) => prev.replace(newLine, ''));
}, []);
// when str changes reset lines, and set remainingStr to str
useEffect(() => {
setLines([]);
setRemainingStr(str);
}, [str]);
return (
<>
<View style={[styles.container, containerStyle]}>
<ScrollView style={{ flex: 1 }}>
{lines.map((line, i) => (
<Text
{...textProps}
style={[textProps.style, lineStyles[i % lineStyles.length]]}>
{line}
</Text>
))}
</ScrollView>
{/* this view will be invisible*/}
{remainingStr.length > 0 && (
<View style={{ opacity: 0 }}>
<Text
{...textProps}
onTextLayout={onTextLayout}
style={[
textProps.style,
// use lines.length to get proper style
lineStyles[lines.length % lineStyles.length],
]}>
{remainingStr}
</Text>
</View>
)}
</View>
</>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
height:'50%'
},
});
// be careful when passing non memoized array/objects
export default memo(MultiLineText)
Its important to note that objects/arrays that arent memoized/state/refs will cause the memoized component to re-render, even if the values are static e.g
<MultiLineText
containerStyle={{
width: '100%',
height: 200,
backgroundColor: '#eef',
alignSelf: 'center',
alignItems: 'center',
}}
style={styles.defaultTextStyle}
str={text}
lineStyles={[styles.text,styles.text2]}
/>
containerStyle and lineStyles are getting new objects and arrays every time its parent component re-render, which will make MultiLineText re-render (even though its memoized). After moving the containerStyle to the stylesheet and memoizing lineStyles re-rendering becomes better:
const lineStyles = React.useMemo(()=>{
return [styles.text,styles.text2]
},[])
return (
<View style={styles.container}>
<TextInput onChangeText={setText} label="Enter some text" value={text} />
<MultiLineText
containerStyle={styles.textContainer}
style={styles.defaultTextStyle}
str={text}
lineStyles={lineStyles}
/>
</View>

How do I build a multi-card carousel?

I'm trying to build something like this in React Native. It will stretch across the whole page and will loop infinitely, there will be a 'next' and 'previous' button.
I'm new to React Native (coming from React), so am a little unsure about how to implement it.
I found this guide on YouTube helpful to get something very basic up and running.
Here is the code I have so far:
import React, {useCallback, useEffect, useRef, useState} from 'react';
import {withTheme} from 'react-native-paper';
import {
View,
StyleSheet,
Text,
Dimensions,
Image,
FlatList,
Pressable,
} from 'react-native';
import PrismicText from '../prismicText';
const {width: windowWidth, height: windowHeight} = Dimensions.get('window');
const Slide = ({data}) => {
return (
<View
style={{
height: 400,
width: 300,
justifyContent: 'center',
alignItems: 'center',
marginRight: 15,
}}>
<Image
source={{uri: data.image}}
style={{width: '100%', height: '100%', borderRadius: 16}}></Image>
</View>
);
};
const Carousel = ({slice, theme}) => {
const slideList = slice.items.map((item, index) => {
return {
id: index,
image: item.image.url,
};
});
const {colors, isTabletOrMobileDevice} = theme;
const styles = isTabletOrMobileDevice ? mobileStyles : desktopStyles;
const flatListRef = useRef(null);
const viewConfig = {viewAreaCoveragePercentThreshold: 50};
const [activeIndex, setActiveIndex] = useState(4);
const onViewRef = useRef(({changed}) => {
if (changed[0].isViewable) {
setActiveIndex(changed[0].index);
}
});
const handlePressLeft = () => {
if (activeIndex === 0)
return flatListRef.current?.scrollToIndex({
animated: true,
index: slideList.length - 1,
});
flatListRef.current?.scrollToIndex({
index: activeIndex - 1,
});
};
const handlePressRight = () => {
if (activeIndex === slideList.length - 1)
return flatListRef.current?.scrollToIndex({
animated: true,
index: 0,
});
flatListRef.current?.scrollToIndex({
index: activeIndex + 1,
});
};
return (
<>
<View
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
paddingHorizontal: 16,
paddingVertical: 8,
}}>
<Pressable style={[styles.chevron]} onPress={handlePressLeft}>
Left
</Pressable>
<Pressable style={[styles.chevron]} onPress={handlePressRight}>
Right
</Pressable>
</View>
<FlatList
ref={ref => (flatListRef.current = ref)}
data={slideList}
horizontal
showsHorizontalScrollIndicator={false}
snapToAlignment="center"
pagingEnabled
viewabilityConfig={viewConfig}
onViewableItemsChanged={onViewRef.current}
renderItem={({item}, i) => <Slide data={item} />}
keyExtractor={item => item}
/>
<View style={styles.index}>
<Text category={'c2'} style={styles.indexText}>
{activeIndex + 1} of {slideList.length} photos
</Text>
</View>
</>
);
};
const mobileStyles = StyleSheet.create({});
const desktopStyles = StyleSheet.create({});
export default withTheme(Carousel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
The problems I'm experiencing with this code:
I am setting the initial state of the active index to 4, but active index always starts at 0
Clicking the 'right' button doesn't seem to change the active index
Clicking the 'right' button will move the carousel along by 1 increment, but it won't go any further (even on smaller viewports like mobile where you can only see 1.5 cards, so it should move along many times to be able to see all of the cards)
Clicking the 'left' button seems to have the same issues as above
There is no infinite loop of the slides
My feeling is that there are two issues to be addressed:
Active index is broken and needs to be fixed
Modifications required to make the number of cards on the viewport responsive
I've spent a lot of time looking at this and can't seem to figure it out. Any help would be much appreciated.
The first issue is easy to fix. You are expecting that the FlatList scrolls initially to the initial activeIndex, but you are not telling the FlatList to do so. There is a prop called initialScrollIndex that is designed for this purpose.
<FlatList
initialScrollIndex={4}
...
The second issue is caused by a faulty implementation of the functions handlePressLeft and handlePressRight as well as providing
const onViewRef = useRef(({changed}) => {
if (changed[0].isViewable) {
setActiveIndex(changed[0].index);
}
});
I have removed the above completely.
I have changed the activeIndex state to the following.
const [activeIndex, setActiveIndex] = useState({index: 4, direction: 'right'});
I have changed the handlePressLeft and handlePressRight functions to the following.
const handlePressLeft = () => {
setActiveIndex((prev) => ({index: prev.index - 1, direction: 'left'}));
};
const handlePressRight = () => {
setActiveIndex((prev) => ({index: prev.index + 1, direction: 'right'}));
};
I have created an effect as follows.
React.useEffect(() => {
if (activeIndex.index === slideList.length - 1 && activeIndex.direction === 'right') {
setActiveIndex({index: 0, direction: 'right'});
} else if (activeIndex.index < 0 && activeIndex.direction === 'left') {
setActiveIndex({index: slideList.length - 2, direction: 'left'})
} else {
flatListRef.current?.scrollToIndex({
animated: true,
index: activeIndex.index,
});
}
}, [activeIndex, slideList.length]);
I have implemented an adapted snack without images and using a dummy array.
You can use the below third-party library to achieve the above one quickly.
react-native-snap-carousel
You can check all the examples and use them according to your requirement.
Hope it will help you!
You should try react-native-reanimated-carousel.
Why?
highly customizable + easy and fast to implement any carousel
It's new and it uses react-native-reanimated for better performance (by running animations on the UI thread, rather than on JS thread)
solves all the issues that react-native-snap-carousel has (which is deprecated and has lots of bugs)
solves all the issues that you have and handles many edge cases that you may have forgotten about (in case you want to implement it by yourself)

Left-align a scaled View/Text with react-native's Animated API

I a trying to build a 'Material-UI-like' TextInput with a large label that shrinks down when the field is selected.
I am having issues with scaling the label. Applying a transform: [{scale: ...}] shrinks the Text, but does so around the center of the field. I am failing to keep the label left-aligned during the scaling process, as I'd need to dynamically be able to access the view's width to offset it, but I can't seem to be able to get it using normal means(i.e. onLayout, which does not seem to be triggered during the animation).
Here is an example demonstrating the issue:
import React from 'react';
import { View, Text, TextInput, Animated } from 'react-native';
export const F = (): JSX.Element => {
const scale = React.useRef(new Animated.Value(0.0)).current;
React.useEffect(() => {
const animation = Animated.timing(scale, {
toValue: 1.0,
duration: 1000,
useNativeDriver: true,
});
animation.start();
}, []);
return (
<View style={{ backgroundColor: 'red' }}>
<Animated.View
style={{
transform: [
{
scale: scale.interpolate({
inputRange: [0, 1],
outputRange: [1, 0.5],
}),
},
],
backgroundColor: 'yellow',
}}
onLayout={(e) => console.log({ view: e.nativeEvent.layout })}>
<Text onLayout={(e) => console.log({ text: e.nativeEvent.layout })}>
Label
</Text>
</Animated.View>
<TextInput style={{ backgroundColor: 'blue' }} />
</View>
);
};
Example after the text has been scaled by half:
Note how the yellow view (Text) is no longer left aligned because of the scaling.
I've created a stack to explain what I am trying to accomplish:
https://snack.expo.dev/#bertrand-caron/trembling-beef-jerky
I'd like the Label View (yellow) to stay left align when scaled, instead of being shrunk centered inside the red view.
I have two solution:
1. For this I have created a snack: https://snack.expo.dev/PFN07UigC .
Let me know if it fits. For left aligning I just used justify-content:'flex-start' to its container.
2. If you wish to calculate it you know the initial size with onLayout and you have the scale let us assume that scale you are using is 0.5 and the onLayout gave you 100 then the margin-left that you are wanted is (width-(width*scale))/2 which is in our case 25. But I don't see any need for that.
In my opinion, you should make the <Animated.Text/> rather than <Animated.View/>. But it will also work.
If you don’t use alignSelf: 'flex-start' it will take the same space as the Parent View.
Here is my solution: https://snack.expo.dev/#fanish/textinput-animation
<Animated.Text
style={{
...textStyle,
transform: [{ scale }],
alignSelf: 'flex-start',
}}>
Label
</Animated.Text>

react native flat list how to force list items to be the same height?

I have a React-Native application where I am using FlatList to display a list of items obtained from the server. The list has 2 columns and I need my list items to be the same height. I put a border around the code rendering my list items but the list items are not the same height. I have tried using flexbox settings to make the view fill the container, but everything I try makes no difference.
I have created a simplified version of my app to illustrate the issue:
See that the red bordered areas are NOT the same height. I need to get these to be the same height.
The grey border is added in the view wrapping the component responsible for a list item and the red border is the root view of the component responsible for a list item. See the code below for clarity.
I can not use the grey border in my application because my application shows empty boxes whilst the component responsible for a list item is getting additional information from the server before it renders itself
Furthermore I can not used fixed sizes for heights.
Application Project structure and code
My code is split up in a manner where the files ending in "container.js" get the data from the server and pass it to its matching rendering component. For example, "MainListContainer" would be getting the list from the server and then pass the list data to "MainList", and "ListItemContainer" would get additional information about the single list item from the server and pass it to "ListItem" to render the actual item. I have kept this model in my simplified application so its as close to my real application as possible.
index.js
import {AppRegistry} from 'react-native';
import MainListContainer from './app/components/MainListContainer';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => MainListContainer);
MainListContainer.js
import React from 'react';
import MainList from './MainList';
const data = [
{id: '1', title: 'Item 1', subtitle: 'A', description: 'This is the first item.'},
{id: '2', title: 'Item 2', subtitle: 'B', description: 'The Big Brown Fox Jumped over the lazy dogs. The Big Brown Fox Jumped over the lazy dogs.',},
];
const MainListContainer = () => {
return ( <MainList items={data} /> );
};
export default MainListContainer;
MainList.js
import React from 'react';
import {StyleSheet, FlatList, View} from 'react-native';
import ListItemContainer from './ListItemContainer';
export default class MainList extends React.Component {
constructor(props) {
super(props);
this.state = { numColumns: 2};
this.renderItem = this.renderItem.bind(this);
}
renderItem({item, index}) {
return (
<View style={styles.flatListItemContainer}> <!-- THIS IS WHERE THE GREY BORDER IS ADDED -->
<ListItemContainer key={index} item={item} />
</View>
);
}
render() {
const {items} = this.props;
const {numColumns} = this.state;
return (
<View>
<FlatList
data={items}
renderItem={this.renderItem}
numColumns={numColumns}
key={numColumns}
keyExtractor={(item) => item.id}
/>
</View>
);
}
};
const styles = StyleSheet.create({
flatListItemContainer: {
flex: 1,
margin: 10,
borderColor: '#ccc',
borderWidth: 1,
},
});
ListItemContainer.js
import React from 'react';
import ListItem from './ListItem';
const ListItemContainer = (props) => {
const { item } = props;
return (
<ListItem item={item} />
);
};
export default ListItemContainer;
ListItem.js
import React from 'react';
import {TouchableHighlight, View, StyleSheet, Image, Text} from 'react-native';
const ListItem = (props) => {
const { item } = props;
return (
<TouchableHighlight
underlayColor="white"
>
<View style={styles.containerView}> <!-- THIS IS WHERE THE RED BORDER IS ADDED -->
<View style={styles.top_row}>
<Image style={styles.image} source={require('../images/placeholder.png')} />
<View style={styles.title_texts}>
<Text style={{fontWeight:'bold'}}>{item.title}</Text>
<Text style={{color: 'rgb(115, 115, 115)'}}>{item.subtitle}</Text>
</View>
</View>
<Text>{item.description}</Text>
</View>
</TouchableHighlight>
);
};
export default ListItem;
const styles = StyleSheet.create({
containerView: {
padding: 14,
borderColor: 'red',
borderWidth: 1,
},
top_row: {
flex: 1,
flexDirection: 'row',
marginBottom: 10,
},
title_texts: {
flex: 1,
flexDirection: 'column',
},
image: {
alignSelf: 'flex-end',
resizeMode: 'cover',
height: 40,
width: 40,
marginRight: 20
},
});
What I have tried
ListItem.js : move the style onto the "TouchableHighlight" view
ListItem.js : add a view wrapping "TouchableHighlight" view and adding style there
ListItem.js : added "alignItems:'stretch' on the "TouchableHighlight, added it to the "containerView" style, tried it on the description field too
same as "alignItems" but used "alignedSelf" instead
same as "alignItems" but used "alignedContent" instead
tried using "flexGrow" on different views (container, description)
You can measure the height of every element in the list and when you determine the maximum height, you can use that height for every element in the list.
const Parent = ({ ...props }) => {
const [maxHeight, setMaxHeight] = useState<number>(0);
const computeMaxHeight = (h: number) => {
if (h > maxHeight) setMaxHeight(h);
}
return (
<FlatList
data={props.data}
renderItem={({ item }) => (
<RenderItem
item={item}
computeHeight={(h) => computeMaxHeight(h)}
height={maxHeight}
/>
)}
....
/>
)
}
The Items:
const RenderItem = ({...props }) => {
return (
<View
style={{ height: props.height }}
onLayout={(event) => props.computeHeight(event.nativeEvent.layout.height)}
>
<Stuffs />
</View>
)
}
This is a very non-performant way of achieving this. I would avoid this if I have a long list or any list of more than a few items. You however can put certain checks in place to limit rerendering etc. Or alternatively if it is only text that will affect the height, then you can only measure the height of the element with the most text and use that element's height for the rest.
Instead of set fixed width height, you can use flex box to achieve it. I just solved the issue by removing alignSelf at the FlatList and add alignItems center on it.
Wrap the flatList in flex box with align item center, you can add the code in your MainList.js file, the first <View>, i.e:
render() {
const {items} = this.props;
const {numColumns} = this.state;
return (
<View style={{flex: 1, alignItems: 'center'>
<FlatList
data={items}
renderItem={this.renderItem}
numColumns={numColumns}
key={numColumns}
keyExtractor={(item) => item.id}
/>
</View>
);
If still not reflected, you may try to add flex:1, alignItems center in FlatList style props.
You are missing a very basic concept of giving fixed height to the flatlist items, in your ListItem.js, try to set height:200 in containerView. Let me know if that works for you

Can we Change Colors to Dropdown Label in reactnative

I am new to React native and working on a project on that, I am using react-native material-dropdown for using drop down component .i want to change the label color of drop-down but i am unable to do it because i didn't find label color property to change .could someone help me with this as the label is taking default color as black for the label text.
textColor:'#FFF'
tintColor:'#ffffff'
I tried giving these two styles also but it doesn't work for me.
Do anyone have a solution for that?
Thanks in advance
<Dropdown
onChangeText={ (val) => this.changeDate(val)}
label='All Dates'
data={data}
style = {{color: 'white'}} //for changed text color
baseColor="rgba(255, 255, 255, 1)" //for initial text color
/>
Use itemTextStyle and textColor.
<Dropdown
containerStyle={{width:200}}
label='Favorite Fruit'
itemTextStyle={{backgroundColor:"blue",textColor:"white"}}
textColor="#FFF"
data={data}
/>
Here is expo example.
If you are using DropDownPicker from react-native-dropdown-picker, then you should do
labelStyle = {{
fontSize: 15,
color:'white'
}}
This will change the text color. Refer here
import React, {useState, useEffect} from 'react';
import {Dropdown} from 'react-native-element-dropdown';
function DropdownComponent() {
const [value, setValue] = useState(null);
const dropDownData = [
{label: 'Option 1', value: '0'}
{label: 'Option 2', value: '1'}
{label: 'Option 3', value: '2'}
{label: 'Option 4', value: '3'}
{label: 'Option 5', value: '4'}
];
return (
<Dropdown
selectedTextProps={{
style: {
fontSize: 20,
color: 'blue',
},
}}
selectedTextStyle={{
fontSize: 13,
color: 'black',
}}
data={dropDownData}
iconColor="black"
iconStyle={{width: 36, height: 36}}
maxHeight={200}
labelField="label"
valueField="value"
value={value}
onChange={(item) => {
setValue(item.value);
}}
/>
);
}
export default DropdownComponent;