How can i access my state variables in StyleSheet? - reactjs

I calculate various margin's based on the images i'm displaying in my app, which range in different pixel widths each time images are selected, so my need us quite dynamic. Once i calculate the margin widths, i save them in state variables marginL and marginR.
However i can't seem to access these in StyleSheet, i just get an error message to say marginLeft is undefined.
const styles = StyleSheet.create({
container: {
flex: 1,
},
gap: {
flex: 0.5,
marginLeft: this.state.marginL,
marginRight: this.state.marginR
}
})
How do i get access to my variables?

I'm not sure about dynamically changing in StyleSheet value. But when you calculate the margin widths you can override your style something like below
<View style={[styles.gap, {marginLeft: this.state.marginL, marginRight: this.state.marginR}]} />
Check complete example
import React, { Component } from "react";
import { View, StyleSheet } from "react-native";
export default class App extends Component {
state = {
marginL: 10,
marginR: 20
};
render() {
return (
<View style={styles.container}>
<View style={[ styles.gap, { marginLeft: this.state.marginL, marginRight: this.state.marginR }]} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "red"
},
gap: {
flex: 0.5,
marginLeft: 0,
marginRight: 0,
backgroundColor: "green"
}
});
This not be the optimal solution but hope this helps you. Feel free for doubts.

Related

In NativeBase, how can I avoid inline styling props of component and write it separately and then pass it

I am just trying to write a clean code and avoid lots thing in same tag. For example: Text and Box component have could have so many styling props, So is there any way I can write it separately and they pass it as a whole object as style.
import { Box, extendTheme, NativeBaseProvider, Progress, Text, View } from 'native-base'
import React, { FC } from 'react'
const TrainingList: FC = () => {
return (
<NativeBaseProvider>
<Box my="2">
<Text fontSize="16" lineHeight="21.8" bold> Annual Training </Text>
<View my="2" >
<Text fontSize="14" lineHeight="19.8"> Due in 2 days (01/12/22) </Text>
<Text fontSize="14" lineHeight="19.8"> 50% complete / 10 hrs left </Text>
</View>
<Progress rounded="12" colorScheme="warning" bg="#D7D7D7" size="sm" value={65} mx={0} />
</Box>
<Box mt="5">
This is Box2
</Box>
</NativeBaseProvider>
)
}
export default TrainingList
In my eyes, the best approach will be to add variants to the NativeBase Text and Box component. It'll keep your code but also you'll be able to share consistent style throughout the codebase.
And if you wanna know HOW? I'm sharing a few resources to follow.
Resource:
Official Docs: First place to go.
Snack: A demo snack to show how to add variants.
Blog: To better understand how to effectively customise NativeBase components.
You can use StyleSheet for that. You can use what you defined under styles on components.
import React from "react";
import { StyleSheet, Text, View } from "react-native";
const App = () => (
<View style={styles.container}>
<Text style={styles.title}>React Native</Text>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 24,
backgroundColor: "#eaeaea"
},
title: {
marginTop: 16,
paddingVertical: 8,
borderWidth: 4,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#61dafb",
color: "#20232a",
textAlign: "center",
fontSize: 30,
fontWeight: "bold"
}
});
export default App;
Yes, that's possible using styled components. You can accept props inside of your styling. Alternatively, I prefer using stylesheets as it's simpler and still keeps your code clean. Ex:
<Box style={styles.boxMain}>
<Text style={styles.textOneStyle}> Annual Training </Text>
<View my="2">
<Text style={styles.textTwoStyle}> Due in 2 days (01/12/22) </Text>
<Text style={styles.textTwoStyle}> 50% complete / 10 hrs left </Text>
</View>
</Box>
);
};
const styles = StyleSheet.create({
textOneStyle: {
fontSize: 16,
lineHeight: 21.8,
fontWeight: "bold"
},
textTwoStyle: {
fontSize: 14,
lineHeight: 19.8,
},
});

Margin in React-Native not working properly

I was trying to make an app on React-Native
To start, I did mere basic where I wanted to make a bottom Navigation
This is what I did at start to test
import React, { Component } from 'react'
import {
StyleSheet,
View,
Text,
Image
} from 'react-native';
class MainScreen extends Component {
constructor () {
super ()
this.board = []
}
render () {
return (
<View style={MainScreenBox}>
<View style={GridBox}>
<Text> Testing..........</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
MainScreenBox: {
display: "flex",
flexDirection: "column"
},
GridBox: {
marginTop: "90%",
marginLeft: 5,
marginRight: 5
}
})
const {
GridBox,
MainScreenBox
} = styles
Here, I did something as simple as marginTop: "90%", expecting the text would come at bottom but it still remains half way on the screen.
Question: Any Idea why this could be happening?
Clean all styles and put this to MainScreenBox style:
const styles = StyleSheet.create({
MainScreenBox: {
flex: 1,
justifyContent:'flex-end'
}
})
and use style={styles.MainScreenBox} to apply in root View. You can refer to flex doc to see how FlexBox works. Also notice that flexDirection is column by default in react native you do not have to set it and display:"flex" neither.
Add a flex weight (flex:1) to your main container.
MainScreenBox: {
flex:1,
display: "flex",
flexDirection: "column"
},

How can I change the color of an icon without re-render (TextField loosing focus)

I am using the package called react-native-phone-input, and when the phone number is changed it runs the function this.updateInfo() which updates the state. In my code, the icon color is dependent on the state and changes based on whether the phone number is valid. This works, however, when the state is changed, the screen re-renders and the keyboard is dismissed since the text field loses focus. Is there another way I can change the icons color? Or is there a way that I can keep the focus on the text field?
This is what I am referring to:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Keyboard} from 'react-native';
import { Icon } from 'react-native-elements';
import KeyboardAccessory from 'react-native-sticky-keyboard-accessory';
import PhoneInput from 'react-native-phone-input';
export default class PhoneLogin extends Component {
constructor() {
super();
this.state = {
valid: "",
type: "",
value: "",
iconColor: "#D3D3D3",
};
this.updateInfo = this.updateInfo.bind(this);
}
updateInfo() {
this.setState({
valid: this.phone.isValidNumber(),
type: this.phone.getNumberType(),
value: this.phone.getValue().replace(/[- )(]/g,''),
});
}
render() {
return (
<View style={styles.container}>
<PhoneInput
ref={ref => {
this.phone = ref;
}}
style={{height: 50, borderColor:'#44c0b9', borderBottomWidth:2}}
onChangePhoneNumber={ (phone) => {this.updateInfo()} }
/>
<KeyboardAccessory backgroundColor="#fff">
<View style={{ alignItems: 'flex-end', padding:10 }}>
<Icon
raised
reverse
color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"}
name='arrow-right'
type='font-awesome'
onPress={ Keyboard.dismiss()}
/>
</View>
</KeyboardAccessory>
</View>
);
}
}
let styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
padding: 20,
paddingTop: 60
},
info: {
// width: 200,
borderRadius: 5,
backgroundColor: "#f0f0f0",
padding: 10,
marginTop: 20
},
button: {
marginTop: 20,
padding: 10
}
});
In your onPress of your Icon you need to send an arrow function.
The Icon should be like this
<Icon
raised
reverse
color={(this.state.valid) ? "#44c0b9" : "#D3D3D3"
name='arrow-right'
type='font-awesome'
onPress={() => Keyboard.dismiss()}
/>
The problem was the Keyboard.dismiss() was immediately running every time the component re-rendered thus dismissing your keyboard.
Hope this helps!

Using a button to change the color of text

I'm trying to create a simple React Native app that:
Renders "Hello, [name]!" when a user enters a name (this part works)
Changes the "Hello, [name]!" text color when a button is pressed.
Any ideas as to how I should go about this?
I gave this an initial state of black, but that doesn't even seem to be doing anything.
What I want to happen is to trigger makeRed when the red button is clicked, which will turn the text red. Once I have this working, I'll add more color buttons.
Thank you!
See below for my App.js code. All other files were left in their default state.
import React, { Component } from 'react';
import {
AppRegistry,
Platform,
StyleSheet,
Text,
TextInput,
View,
Button
} from 'react-native';
export default class App extends Component<{}> {
constructor(props) {
super(props);
this.state = {
text: 'World',
color: 'black'
};
}
makeRed = () => {
this.setState({
color: 'red'
});
}
render() {
return (
<View style={styles.container}>
<Text style={[styles.welcome, {color: undefined}]}>
Hello, {this.state.text}!
</Text>
<TextInput
style={styles.instructions}
placeholder="Enter a name here!"
onChangeText={(text) => this.setState({text})}
/>
<Button
title='⬤'
onPress={this.makeRed}
color='red'
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 40,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
Here's a screenshot of the app for reference:
app screenshot
All you need to do is change this :
style={[styles.welcome, {color: undefined}]}
To
style={[styles.welcome, {color : this.state.color }]}
Please check : WORKING DEMO
color is not referenced as a property of state , in the style of the Text component. Try this as the Text element:
<Text style={{color: this.state.color, ...styles.welcome}}>
Hello, {this.state.text}!
</Text>
And, makeRed needs to be have it's context bound in the constructor, or else this.setState will be undefined. Like this (under super(props)):
this.makeRed = this.makeRed.bind(this)

How to add stateless component to a touchable component

I am trying to add a stateless component to my button.
const button = ({onButtonPress, buttonText}) => {
return (
<TouchableHighlight
onPress={() => onButtonPress()}>
<ButtonContent text={buttonText}/>
</TouchableHighlight>
)
};
and get this error:
Warning: Stateless function components cannot be given refs (See ref "childRef"
in StatelessComponent created by TouchableHighlight).
Attempts to access this ref will fail.
I have read up on the issue but I am still new to javascript and RN and have not found a solution. Any help would be appreciated.
full code:
GlossaryButtonContent:
import React from 'react';
import {
View,
Text,
Image,
StyleSheet
} from 'react-native';
import Colours from '../constants/Colours';
import {
arrowForwardDark,
starDarkFill
} from '../assets/icons';
type Props = {
text: string,
showFavButton?: boolean
}
export default ({text, showFavButton} : Props) => {
return (
<View style={styles.container}>
{showFavButton &&
<Image
style={styles.star}
source={starDarkFill}/>}
<Text style={[styles.text, showFavButton && styles.favButton]}>
{showFavButton ? 'Favourites' : text}
</Text>
<Image
style={styles.image}
source={arrowForwardDark}
opacity={showFavButton ? .5 : 1}/>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
alignItems: 'center'
},
favButton: {
marginLeft: 10,
color: Colours.darkTextHalf
},
text: {
flex: 1,
paddingTop: 5,
marginLeft: 20,
fontFamily: 'Bariol-Bold',
fontSize: 24,
color: Colours.darkText
},
image: {
marginRight: 20
},
star: {
marginLeft: 10
}
});
GlossaryButton:
import React from 'react';
import {
TouchableHighlight,
StyleSheet
} from 'react-native';
import Colours from '../constants/Colours';
import ShadowedBox from './ShadowedBox';
import GlossaryButtonContent from './GlossaryButtonContent';
type Props = {
buttonText: string,
onButtonPress: Function,
rowID: number,
sectionID?: string,
showFavButton?: boolean
}
export default ({buttonText, onButtonPress, rowID, sectionID, showFavButton} : Props) => {
return (
<ShadowedBox
style={styles.container}
backColor={showFavButton && Colours.yellow}>
<TouchableHighlight
style={styles.button}
underlayColor={Colours.green}
onPress={() => onButtonPress(rowID, sectionID)}>
<GlossaryButtonContent
text={buttonText}
showFavButton={showFavButton}/>
</TouchableHighlight>
</ShadowedBox>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
height: 60,
marginBottom: 10,
borderRadius: 5
},
button: {
flex: 1,
borderRadius: 5
}
});
Basically, Stateless components cannot have refs.
So, having a stateless component in the middle of the render tree will create a void in the ref chain, meaning you cannot access lower-down components.
So, the problem comes from trying to do this:
let Stateless = (props) => (
<div />
);
let Wrapper = React.createClass({
render() {
return <Stateless ref="stateeee" />
}
});
TouchableHighlight needs to give a ref to its child. And this triggers that warning.
Answer:
You can't actually make a stateless component a child of TouchableHighlight
Solution:
Use createClass or class to create the child of TouchableHighlight, that is GlossaryButtonContent.
See this github issue for more info and this one

Resources