Edit underline color in react-native-material-dropdown on iOS without changing arrow and label color - react-native

I am using react-native-material-dropdown for a form where I also use RN TextInput so I want a consistent look between both.
I want to have a black label header and a light grey underline
For Android I use underlineColorAndroid={'transparent'} and that works fine.
The problem is on iOS if I change the baseColor property, it automatically changes the dropdown arrow, the underline and the label.
How could set the color of the label and the underline separately?
import { Dropdown } from 'react-native-material-dropdown'
//...
<Dropdown
underlineColorAndroid="transparent"
label={'BILLING TYPE'}
labelFontSize={12}
labelTextStyle={styles.dropdownLabel}
itemTextStyle={styles.dropdownItem}
style={styles.dropdownMainText}
style = {{color: Colors.black}}
baseColor={Colors.black}
value={'Paper'}
data={billingTypes}
onChangeText={value => this.onEditField(value)}
/>
If I set baseColor={Colors.black} (which I want) the underline becomes black instead of grey (which I don't want).
If I set baseColor={Colors.rose}, all 3 elements change colors: label, arrow and underline.
here is my styles.js file where nothing special happens
export default StyleSheet.create({
//...
dropdownLabel: {
textTransform: 'uppercase',
color: Colors.black,
},
dropdownItem: {
fontSize: Fonts.size.tiny,
color: Colors.black,
},
dropdownMainText: {
},
});
const colors = {
black: '#252525',
rose: '#e6968f',
};

The color you would like to change in the Dropdown object is currently running in the function. You cannot set it separately because you do not specify a separate color for the underline.
/dropdown/index.js
renderRipple() {
let {
baseColor,
rippleColor = baseColor,
rippleOpacity,
rippleDuration,
rippleCentered,
rippleSequential,
} = this.props;
let { bottom, ...insets } = this.rippleInsets();
let style = {
...insets,
height: this.itemSize() - bottom,
position: 'absolute',
};
return (
<Ripple
style={style}
rippleColor={rippleColor}
rippleDuration={rippleDuration}
rippleOpacity={rippleOpacity}
rippleCentered={rippleCentered}
rippleSequential={rippleSequential}
ref={this.updateRippleRef}
/>
);
}

I found it! As explained here: https://github.com/n4kz/react-native-material-dropdown/issues/23
<Dropdown
//
inputContainerStyle={{ borderBottomColor: Colors.midGrey, borderBottomWidth: 1 }}
/>
with const colors = {midGrey: 'rgba(214, 219, 224, 1)'};

Related

Setting card height programmatically in React Native

In my React Native app, I want to display cards using simple <View>'s that will have a set height to begin with and display two lines of text.
If the text is longer than two lines, I want to display a "more" button which will expand the height of the view to fit all the text when clicked.
My question is how to determine/calculate the height?
The approach I'm thinking is to use two different style classes and programmatically switch them but I'm not sure how to dynamically figure out the height of the <View> so that all the text would fit into it, however long it may be.
const cardStyle = this.props.moreButtonClicked ? "card-long" : "card-std";
return (
<View style={cardStyle}>
<Text>
{
this.props.cardContent.length <= 120
? this.props.cardContent
: this.props.moreButtonClicked
? this.props.cardContent
: this.props.cardContent.substring(0, 119)
}
</Text>
</View>
);
Specifically, how do I figure out the right height for my card-long style class? Or is there a better approach to handling this? Thanks.
You can determine text height before rendering the text by using this library: https://github.com/aMarCruz/react-native-text-size
Here is an example:
import rnTextSize, { TSFontSpecs } from 'react-native-text-size'
type Props = {}
type State = { width: number, height: number }
// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
fontFamily = undefined,
fontSize = 24,
fontStyle = 'italic',
fontWeight = 'bold',
}
const text = 'I ❤️ rnTextSize'
class Test extends Component<Props, State> {
state = {
width: 0,
height: 0,
}
async componentDidMount() {
const width = Dimensions.get('window').width * 0.8
const size = await rnTextSize.measure({
text, // text to measure, can include symbols
width, // max-width of the "virtual" container
...fontSpecs, // RN font specification
})
this.setState({
width: size.width,
height: size.height
})
}
// The result is reversible
render() {
const { width, height } = this.state
return (
<View style={{ padding: 12 }}>
<Text style={{ width, height, ...fontSpecs }}>
{text}
</Text>
</View>
)
}
}

React Native Paper Text Input - Adjusting label color at the initial state

I want to adjust the outlined react-native-paper TextInput label color at the initial state (not onFocus). This is my OutlinedInput component:
import * as React from 'react';
import { TextInput } from 'react-native-paper';
const OutlinedInput = (props) => {
return (
<TextInput
mode='outlined'
label={props.label}
placeholder={props.placeholder}
placeholderTextColor='white'
secureTextEntry={props.secureTextEntry}
multiline={props.multiline}
keyboardType={props.keyboardType}
value={props.value}
onChangeText={(value) => props.onChangeText(value)}
style={props.style}
theme={props.theme}
/>
);
};
export default OutlinedInput;
In my Register component, I created an OutlinedInput component inside it:
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<OutlinedInput
label={'User Name'}
value={userName}
onChangeText={(userName) => setUserName(userName)}
style={{ color: 'white', backgroundColor: 'rgb(35,39,42)',
borderRadius: 5, width: '75%', height: '5%'
}}
theme={{ colors: { text: 'white', primary: 'rgb(33, 151, 186)' } }}
/>
</View>
I added this line at the top of Register component:
const [userName, setUserName] = useState('');
The screenshot of my program if I do not click the input:
This is the screenshout for clicking the input:
As you can see, the color of label User Name is black. I want to set this to white. When clicking on it, it works as expected, but the initial state of the color of the label is not what I want.
I tried to solve this problem using placeholder. I added placeholder props to the OutlinedInput and change placeholder color to white, but in this case, placeholder didn't become outlined. When I tried anything about placeholder, it didn't become outlined.
How can I adjust the label color to see it as white after opening the program?
You need to replace TextInput property:
placeholderTextColor='white'
with:
theme={{
colors: {
placeholder: 'white'
}
}}
In order to adjust label color in React Native Paper v5 you have to update this prop:
theme={{
colors: {
onSurfaceVariant: 'white'
}
}}
I don't get why they made it so unsemantic and inaccessible (it's not even in their Docs)

Implementing dark mode in React Native sensibly

I'm trying to add dark mode support to my React Native app. I will have a flag in a mobx store mode which will be light or dark as appropriate.
In order to tie this into an existing app, I wanted to, if possible, keep the existing style definitions and only override when needed (rather than rewrite everything to a light and a dark theme).
I came up with a function like the following to return the appropriate styles based on the current mode:
function getStyle(style) {
let ret = [styles[style]];
if (
styles.hasOwnProperty(Store.mode) &&
styles[Store.mode][style] !== "undefined"
) {
ret.push(styles[Store.mode][style]);
}
return ret;
}
The view would be rendered as such:
...
<View style={getStyle("container")}>
<Text style={getStyle("text")}>Some text</Text>
</View>
...
The styles:
const styles = {
dark: {
container: {
backgroundColor: "#000"
},
text: {
color: "#fff"
}
},
container: {
padding: 20,
backgroundColor: "#fff"
},
text: {
fontSize: 18,
color: "#000"
}
};
Now this works, but I'm not sure if it's coming at some performance cost I'm unaware of right now (the use of the function, using a style object instead of StyleSheet.create...), or if there's a much simpler way I can't see for the trees. I'd rather not do a ternary inline on every element either.
I ended up going a slightly different way, in that I'd add extra styles depending on the current mode, e.g.
<View style={[styles.container, theme[Store.mode].container]}>
<Text style={[styles.text, theme[Store.mode].text]}>Some text</Text>
</View>
And then using the theme var to override
const theme = {
light: {},
dark: {
container: {
backgroundColor: "#000"
},
text: {
color: "#fff"
}
}
};
const styles = {
container: {
padding: 20,
backgroundColor: "#fff"
},
text: {
fontSize: 18,
color: "#000"
}
};
I would suggest taking a look at the Context api in ReactJS. It gives a good out of the box solution for maintaining global data around the component tree.
You can use React.createContext() and react-native-paper
This module makes it simple to change the background with just a button. I made a simple example for you.
I made an example link.

How to get text size or view size before rendering in React Native

I have found UIManager and onLayout, but all of them can get only the size after rendering.
Are there any 3rd party libraries or APIs to do this before rendering?
The Image component has something like:
var image = new Image();
image.src="??"
image.onload(()=>image.height)
But how about getting the dimensions of a Text or a View?
I think this would help you. From here you can get the Dimensionn of the view.
I don't know if this is possible. But as a workaround you could make the elements invisible by changing their colors or opacity, then calculate the dimensions, then make some changes etc. and then make it visible.
If you are still looking for a solution, I suggest using react-native-text-size. it allows you to get text dimensions before rendering it by using async functions. here is an example of how to use it to achieve what you need.
import rnTextSize, { TSFontSpecs } from 'react-native-text-size'
type Props = {}
type State = { width: number, height: number }
// On iOS 9+ will show 'San Francisco' and 'Roboto' on Android
const fontSpecs: TSFontSpecs = {
fontFamily = undefined,
fontSize = 24,
fontStyle = 'italic',
fontWeight = 'bold',
}
const text = 'I ❤️ rnTextSize'
class Test extends Component<Props, State> {
state = {
width: 0,
height: 0,
}
async componentDidMount() {
const width = Dimensions.get('window').width * 0.8
const size = await rnTextSize.measure({
text, // text to measure, can include symbols
width, // max-width of the "virtual" container
...fontSpecs, // RN font specification
})
this.setState({
width: size.width,
height: size.height
})
}
// The result is reversible
render() {
const { width, height } = this.state
return (
<View style={{ padding: 12 }}>
<Text style={{ width, height, ...fontSpecs }}>
{text}
</Text>
</View>
)
}
}

How to set background color of view transparent in React Native

This is the style of the view that i have used
backCover: {
position: 'absolute',
marginTop: 20,
top: 0,
bottom: 0,
left: 0,
right: 0,
}
Currently it has a white background. I can change the backgroundColor as i want like '#343434' but it accepts only max 6 hexvalue for color so I cannot give opacity on that like '#00ffffff'. I tried using opacity like this
backCover: {
position: 'absolute',
marginTop: 20,
top: 0,
bottom: 0,
left: 0,
right: 0,
opacity: 0.5,
}
but it reduces visibility of view's content.
So any answers?
Use rgba value for the backgroundColor.
For example,
backgroundColor: 'rgba(52, 52, 52, 0.8)'
This sets it to a grey color with 80% opacity, which is derived from the opacity decimal, 0.8. This value can be anything from 0.0 to 1.0.
The following works fine:
backgroundColor: 'rgba(52, 52, 52, alpha)'
You could also try:
backgroundColor: 'transparent'
Try this backgroundColor: '#00000000'
it will set background color to transparent, it follows #rrggbbaa hex codes
Surprisingly no one told about this, which provides some !clarity:
style={{
backgroundColor: 'white',
opacity: 0.7
}}
Try to use transparent attribute value for making transparent background color.
backgroundColor: 'transparent'
You should be aware of the current conflicts that exists with iOS and RGBA backgrounds.
Summary: public React Native currently exposes the iOS layer shadow
properties more-or-less directly, however there are a number of
problems with this:
1) Performance when using these properties is poor by default. That's
because iOS calculates the shadow by getting the exact pixel mask of
the view, including any tranlucent content, and all of its subviews,
which is very CPU and GPU-intensive. 2) The iOS shadow properties do
not match the syntax or semantics of the CSS box-shadow standard, and
are unlikely to be possible to implement on Android. 3) We don't
expose the layer.shadowPath property, which is crucial to getting
good performance out of layer shadows.
This diff solves problem number 1) by implementing a default
shadowPath that matches the view border for views with an opaque
background. This improves the performance of shadows by optimizing for
the common usage case. I've also reinstated background color
propagation for views which have shadow props - this should help
ensure that this best-case scenario occurs more often.
For views with an explicit transparent background, the shadow will
continue to work as it did before ( shadowPath will be left unset,
and the shadow will be derived exactly from the pixels of the view and
its subviews). This is the worst-case path for performance, however,
so you should avoid it unless absolutely necessary. Support for this
may be disabled by default in future, or dropped altogether.
For translucent images, it is suggested that you bake the shadow into
the image itself, or use another mechanism to pre-generate the shadow.
For text shadows, you should use the textShadow properties, which work
cross-platform and have much better performance.
Problem number 2) will be solved in a future diff, possibly by
renaming the iOS shadowXXX properties to boxShadowXXX, and changing
the syntax and semantics to match the CSS standards.
Problem number 3) is now mostly moot, since we generate the shadowPath
automatically. In future, we may provide an iOS-specific prop to set
the path explicitly if there's a demand for more precise control of
the shadow.
Reviewed By: weicool
Commit: https://github.com/facebook/react-native/commit/e4c53c28aea7e067e48f5c8c0100c7cafc031b06
Adding reference of React-Native Version 0.64
Named colors
Named Colors: DOCS
In React Native you can also use color name strings as values.
Note: React Native only supports lowercase color names. Uppercase color names are not supported.
transparent#
This is a shortcut for rgba(0,0,0,0), same like in CSS3.
Hence you can do this:
background: {
backgroundColor: 'transparent'
},
Which is a shortcut of :
background: {
backgroundColor: 'rgba(0,0,0,0)'
},
In case you have hex color, you can convert it to rgba and set the opacity there:
const hexToRgbA = (hex, opacity) => {
let c;
if (/^#([A-Fa-f0-9]{3}){1,2}$/.test(hex)) {
c = hex.substring(1).split('');
if (c.length === 3) {
c = [c[0], c[0], c[1], c[1], c[2], c[2]];
}
c = `0x${c.join('')}`;
return `rgba(${[(c >> 16) & 255, (c >> 8) & 255, c & 255].join(',')},${opacity})`;
}
throw new Error('Bad Hex');
};
const color = '#1f8b7f'; // could be a variable
return (
<View style={{ backgroundColor: hexToRgbA(color, 0.1) }} />
)
source that helped me
This will do the trick help you,
Add one View element and add style as below to that view
.opaque{
position:'absolute',
backgroundColor: 'black',
opacity: 0.7,
zIndex:0
}
The best way to use background is hex code #rrggbbaa but it should be in hex.
Eg: 50% opacity means 256/2 =128, then convert that value(128) in HEX that will be 80,use #00000080 80 here means 50% transparent.
Here is my solution to a modal that can be rendered on any screen and initialized in App.tsx
ModalComponent.tsx
import React, { Component } from 'react';
import { Modal, Text, TouchableHighlight, View, StyleSheet, Platform } from 'react-native';
import EventEmitter from 'events';
// I keep localization files for strings and device metrics like height and width which are used for styling
import strings from '../../config/strings';
import metrics from '../../config/metrics';
const emitter = new EventEmitter();
export const _modalEmitter = emitter
export class ModalView extends Component {
state: {
modalVisible: boolean,
text: string,
callbackSubmit: any,
callbackCancel: any,
animation: any
}
constructor(props) {
super(props)
this.state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
}
componentDidMount() {
_modalEmitter.addListener(strings.modalOpen, (event) => {
var state = {
modalVisible: true,
text: event.text,
callbackSubmit: event.onSubmit,
callbackCancel: event.onClose,
animation: new Animated.Value(0)
}
this.setState(state)
})
_modalEmitter.addListener(strings.modalClose, (event) => {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {}),
animation: new Animated.Value(0)
}
this.setState(state)
})
}
componentWillUnmount() {
var state = {
modalVisible: false,
text: "",
callbackSubmit: (() => {}),
callbackCancel: (() => {})
}
this.setState(state)
}
closeModal = () => {
_modalEmitter.emit(strings.modalClose)
}
startAnimation=()=>{
Animated.timing(this.state.animation, {
toValue : 0.5,
duration : 500
}).start()
}
body = () => {
const animatedOpacity ={
opacity : this.state.animation
}
this.startAnimation()
return (
<View style={{ height: 0 }}>
<Modal
animationType="fade"
transparent={true}
visible={this.state.modalVisible}>
// render a transparent gray background over the whole screen and animate it to fade in, touchable opacity to close modal on click out
<Animated.View style={[styles.modalBackground, animatedOpacity]} >
<TouchableOpacity onPress={() => this.closeModal()} activeOpacity={1} style={[styles.modalBackground, {opacity: 1} ]} >
</TouchableOpacity>
</Animated.View>
// render an absolutely positioned modal component over that background
<View style={styles.modalContent}>
<View key="text_container">
<Text>{this.state.text}?</Text>
</View>
<View key="options_container">
// keep in mind the content styling is very minimal for this example, you can put in your own component here or style and make it behave as you wish
<TouchableOpacity
onPress={() => {
this.state.callbackSubmit();
}}>
<Text>Confirm</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
this.state.callbackCancel();
}}>
<Text>Cancel</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
</View>
);
}
render() {
return this.body()
}
}
// to center the modal on your screen
// top: metrics.DEVICE_HEIGHT/2 positions the top of the modal at the center of your screen
// however you wanna consider your modal's height and subtract half of that so that the
// center of the modal is centered not the top, additionally for 'ios' taking into consideration
// the 20px top bunny ears offset hence - (Platform.OS == 'ios'? 120 : 100)
// where 100 is half of the modal's height of 200
const styles = StyleSheet.create({
modalBackground: {
height: '100%',
width: '100%',
backgroundColor: 'gray',
zIndex: -1
},
modalContent: {
position: 'absolute',
alignSelf: 'center',
zIndex: 1,
top: metrics.DEVICE_HEIGHT/2 - (Platform.OS == 'ios'? 120 : 100),
justifyContent: 'center',
alignItems: 'center',
display: 'flex',
height: 200,
width: '80%',
borderRadius: 27,
backgroundColor: 'white',
opacity: 1
},
})
App.tsx render and import
import { ModalView } from './{your_path}/ModalComponent';
render() {
return (
<React.Fragment>
<StatusBar barStyle={'dark-content'} />
<AppRouter />
<ModalView />
</React.Fragment>
)
}
and to use it from any component
SomeComponent.tsx
import { _modalEmitter } from './{your_path}/ModalComponent'
// Some functions within your component
showModal(modalText, callbackOnSubmit, callbackOnClose) {
_modalEmitter.emit(strings.modalOpen, { text: modalText, onSubmit: callbackOnSubmit.bind(this), onClose: callbackOnClose.bind(this) })
}
closeModal() {
_modalEmitter.emit(strings.modalClose)
}
Hope I was able to help some of you, I used a very similar structure for in-app notifications
Happy coding