Adding styles to a custom component through App.js in React Native - javascript

Ok guys, I've been trying to figure this out for the past 3 days and I can't find a solution, please keep in mind that I am self-taught and I've been studying react native for like 3 months now.
Anyways, I have a custom button with a defined style and everytime that I render my button it loads with the style presented in its file:
Botaozudo.js:
import React from 'react';
import { Text, TouchableOpacity, StyleSheet } from 'react-native';
export default class Botaozudo extends React.Component {
render() {
const { titulo, evento } = this.props;
return (
<TouchableOpacity
style={styles.button}
onPress={() => evento()}>
<Text style={styles.txtButton}>{titulo}</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
btnAlinhar: {
alignItems: 'flex-end',
marginRight: 20,
paddingTop: 7
},
button: {
backgroundColor: '#a082c9',
width: 100,
height: 40,
borderRadius: 10
},
button2: {
backgroundColor: '#a082c9',
width: 300,
height: 90,
borderRadius: 10
},
txtButton: {
color: '#fff',
fontSize: 20,
textAlign: 'center',
paddingVertical: 5
}
});
Lets say that I want two different buttons on my App.js, one that looks like exactly as above and another one with different size and background color. In my mind I just have to do something like this (for the different one):
<Botaozudo
style={styles.newBtn}
titulo='I am a button'
event={() =>
console.log('yup I am a button')}/>
const styles = StyleSheet.create({
newBtn: {
backgroundColor: '#7c7070',
width: 200,
height: 100
}
});
But the thing is that my Botaozudo doesn't know what that style={} prop means. And what I can't figure out is HOW to make my custom component understand it.
Thanks in advance,

Install https://www.npmjs.com/package/prop-types
Then in Botaozudo.js:
import React from 'react';
import { Text, TouchableOpacity, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
export default class Botaozudo extends React.Component {
static propTypes = {
// Custom style for Botaozudo. Requires object
componentStyle: PropTypes.object,
};
static defaultProps = {
componentStyle: styles,
};
render() {
const { titulo, event, componentStyle } = this.props;
return (
<TouchableOpacity style={componentStyle.newBtn} onPress={() => event()}>
<Text style={styles.txtButton}>{titulo}</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
btnAlinhar: {
alignItems: 'flex-end',
marginRight: 20,
paddingTop: 7,
},
button: {
backgroundColor: '#a082c9',
width: 100,
height: 40,
borderRadius: 10,
},
button2: {
backgroundColor: '#a082c9',
width: 300,
height: 90,
borderRadius: 10,
},
txtButton: {
color: '#fff',
fontSize: 20,
textAlign: 'center',
paddingVertical: 5,
},
});
and in App.js:
<Botaozudo
componentStyle={styles}
titulo='I am a button'
event={() =>
console.log('yup I am a button')}/>
const styles = StyleSheet.create({
newBtn: {
backgroundColor: '#7c7070',
width: 200,
height: 100
}
});

Related

react native hooks can only be called inside body of a function component

i am new to react i need help with the usestate need it to change style to display none saving
the text in state then show use it in the inline css the code is below
import React, { useState, Component, useEffect } from 'react';
import { StyleSheet, Text, View, Alert, Image} from "react-native";
import MashButton from "./src/CustomButton";
import Mashcalculator from "./src/calculator";
import { Textfit } from "react-textfit";
import NetInfo from "#react-native-community/netinfo";
const runstartfunc = (res) =>{
if (res == 'Connected'){
createTwoButtonAlert('continue');
}else{
createTwoButtonAlert('text');
}
}
const unsubscribe = NetInfo.addEventListener(state => {
if(state.isConnected == true){
runstartfunc('Connected');
}else{
runstartfunc('Not Connected');
}
});
const App = () => (
const [hidelogo, setHide] = useState("display:none;");
useEffect(() => {
// Update the document title using the browser API
unsubscribe();
}),
<View style={styles.container}>
<Image id="logo" style={styles.tinyLogo} source={require("./assets/logo.png")} />
<Text id="logo-text" style={[styles.logotext, {hidelogo}]}>Show Bookie</Text>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
paddingLeft: 5,
paddingRight: 5,
backgroundColor: "#2e0739",
alignItems:"center",
justifyContent: "center",
},
logotext: {
fontSize: 25,
color: '#12cfed',
fontWeight: "bold",
},
tinyLogo: {
marginBottom: 10,
width: 80,
height: 80,
},
title: {
marginTop: 16,
paddingVertical: 8,
borderWidth: 4,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#61dafb",
color: "#20232a",
textAlign: "center",
fontSize: 30,
fontWeight: "bold",
marginBottom: 15,
}
});
export default App;
When Ever i run the above code i get this error
ERROR Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
i don't know what could be wrong i will really appreciate if you guys can help me figure this out
import React, { useState, Component, useEffect } from 'react';
import { StyleSheet, Text, View, Alert, Image} from "react-native";
import MashButton from "./src/CustomButton";
import Mashcalculator from "./src/calculator";
import { Textfit } from "react-textfit";
import NetInfo from "#react-native-community/netinfo";
const runstartfunc = (res) =>{
if (res == 'Connected'){
createTwoButtonAlert('continue');
}else{
createTwoButtonAlert('text');
}
}
const unsubscribe = NetInfo.addEventListener(state => {
if(state.isConnected == true){
runstartfunc('Connected');
}else{
runstartfunc('Not Connected');
}
});
const App = () => {
const [hidelogo, setHide] = useState("display:none;");
useEffect(() => {
// Update the document title using the browser API
unsubscribe();
})
return( <View style={styles.container}>
<Image id="logo" style={styles.tinyLogo} source={require("./assets/logo.png")} />
<Text id="logo-text" style={[styles.logotext, {hidelogo}]}>Show Bookie</Text>
</View>
)
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingLeft: 5,
paddingRight: 5,
backgroundColor: "#2e0739",
alignItems:"center",
justifyContent: "center",
},
logotext: {
fontSize: 25,
color: '#12cfed',
fontWeight: "bold",
},
tinyLogo: {
marginBottom: 10,
width: 80,
height: 80,
},
title: {
marginTop: 16,
paddingVertical: 8,
borderWidth: 4,
borderColor: "#20232a",
borderRadius: 6,
backgroundColor: "#61dafb",
color: "#20232a",
textAlign: "center",
fontSize: 30,
fontWeight: "bold",
marginBottom: 15,
}
});
export default App;

When importing page to App.js it shows up blank

I am fairly new to React Native and am struggling to get this page to show up when importing it to App.js. It was working by itself, but once I tried to clean things up and put the code into its own file and just call upon it, things went south.
To break things down;
Welcome.js contains the code of a "welcome page" I am trying to create
App.js is the default file created that basically just calls Welcome
and GetStartedButton is just the code of a button that is imported into Welcome but I dont think its necessary to provide.
When running App.js I am not receiving any errors, my screen is just white!
Thank you for any help, I appreciate it more than you know. I apologize for my ignorance!
It wouldnt surprise me if it was just another typo.
I am sure my code is horrible btw! Assuming my styles were an interesting way to do things! Learning...
Welcome.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button} from 'react-native';
import GetStarted from './src/components/GetStartedButton';
export default class Welcome extends Component {
render() {
return (
<View style={styles.containerMain}>
<View style={styles.containerClub}>
<Text style={styles.title}>Word</Text>
</View>
<View style={styles.containerCaption}>
<Text style={styles.caption}> Words Words Words </Text>
</View>
<View style={styles.containerBottom}>
<GetStarted text='Get Started' color='#E50061' />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
containerMain: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'black',
},
containerClub: {
position: 'absolute',
bottom: 288
},
containerCaption: {
position: 'absolute',
bottom: 250
},
/* To style the button and positioning*/
containerBottom: {
position: 'absolute',
bottom: 100
},
/* To style "Word"*/
title: {
fontSize: 35,
fontWeight: "bold",
},
/* To style "Words Words Words"*/
caption:
{
fontSize: 16
}
}
)
App.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button} from 'react-native';
import Welcome from './src/pages/Welcome';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Welcome/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}
}
);
GetStartedButton.js
import React, { Component } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
const GetStarted = props => {
const content = (
<View style={[styles.button, {backgroundColor: props.color}]}>
<Text style={styles.text}>{props.text}</Text>
</View>
)
return <TouchableOpacity onPress={props.onPress}>{content}</TouchableOpacity>
}
const styles = StyleSheet.create({
button: {
padding: 20,
width: 340,
borderRadius: 8,
alignItems: 'center',
},
text: {
color: 'white',
fontSize: 20,
justifyContent: 'center',
alignItems: 'center',
}
});
export default GetStarted;
The problem is in your Welcome component styles. You colored your texts white, so... it is all white.
const styles = StyleSheet.create({
// (...)
/* To style "word"*/
title: {
color: 'white', // remove it!
fontSize: 35,
fontWeight: "bold",
},
/* To style "words words words"*/
caption:
{
color: 'white', // remove it!
fontSize: 16
}
#edit
Also you did not apply your styles in your App component. It should look like this:
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Welcome/>
</View>
)
}
}
Try changing backgroundColor to something else other than white like
containerMain: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'black'
},

TouchableOpacity is not detecting instant touch

I used TouchableOpacity to make a custom button component but its opacity works after some delay when I touch the button using expo client app.
The code of my component is following:
import React from 'react';
import { StyleSheet, Text, TouchableOpacity } from 'react-native';
const CustomButton = ({ label, btnStyle, textStyle, btnType }) => {
const checkBtnType = type => {
if (type === "small") return styles.btnSmall;
if (type === "medium") return styles.btnMedium;
if (type === "large") return styles.btnLarge;
}
return (
<TouchableOpacity activeOpacity={0.4}
style={{ ...styles.btn, ...checkBtnType(btnType), ...btnStyle }}>
<Text style={{ ...styles.text, ...textStyle }}>{label}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
btn: {
alignItems: "center",
justifyContent: "center",
borderRadius: 25,
},
btnSmall: {
height: 34,
width: 140,
},
btnMedium: {
height: 50,
width: 162,
},
btnLarge: {
height: 50,
width: 347,
},
text: {
fontSize: 14,
fontFamily: 'SFPro-Regular',
fontWeight: "bold",
}
});
export default CustomButton;
I am using my component inside a screen. The for the screen is following:
import React from 'react';
import { SafeAreaView, StyleSheet, View, StatusBar } from 'react-native';
import CustomButton from '../components/customButton';
import Heading from '../components/heading';
import Colors from '../constants/Colors';
const SignUp = (props) => {
return (
<SafeAreaView style={styles.container}>
<StatusBar backgroundColor="#ffffff" barStyle="dark-content" />
<Heading label="Sign up" style={styles.topHeading} />
<Heading label="Sign up with" style={styles.subHeading} />
<CustomButton label="Email" btnType="large" style={{ backgroundColor: Colors.primary }} />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
paddingHorizontal: 10,
},
topHeading: {
fontSize: 24,
paddingTop: 42,
paddingBottom: 180,
},
subHeading: {
fontSize: 14,
alignSelf: "flex-start",
paddingVertical: 20,
}
});
export default SignUp;
I have also used the same component in another project and did not face any issue.
TouchableOpacity wraps its children with Animated.View. It seems your styles affected to animated styles. Are inside { ...styles.btn, ...checkBtnType(btnType), ...btnStyle } some opacity props ?

Unable to create round shape button in react native

I want to create round shape button for my app which is build upon react native. I had tried the code below but both of them didn't work out for me.
Code snippet 1: <Button title="+" rounded="true"/>
Code snippet 2: addButton: {
width: 20,
height: 20,
borderRadius: 40
}
Basically, you have to style up Views and Touchables to look like the button you want. Here's an example of a circular button component:
import React from 'react';
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
export default ({ title, onPress }) => <TouchableOpacity onPress={onPress} style={styles.button}>
<Text style={styles.title}>{title}</Text>
</TouchableOpacity>
const styles = StyleSheet.create({
button: {
width: 50,
height: 50,
borderRadius: 25,
backgroundColor: 'red',
alignItems: 'center',
justifyContent: 'center',
},
title: {
color: 'white',
}
})

React Native Render Issue

I am building a simple weather app and having some issues render the forecast. Not sure if it is the styling. I know the api call through the browser and no errors come from the call in android studio
App.JS
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
import Forecast from './components/Forecast';
import Weather from './components/Weather'
class WeatherApp extends Component {
constructor(props){
super(props);
this.state = {
//setting the state to an empty string while keeping the forecast null
zip: "",
forecast: null
};
}
_handleTextChange = event => {
//this function handles the text change when typing in a zip
let zip = event.nativeEvent.text;
Weather.fetchForecast(zip).then(forecast => {
this.setState({forecast: forecast})
})
}
render() {
let content = null;
if(this.state.forecast !== null) {
content = (
<Forecast
main = {this.state.forecast.main}
description = {this.state.forecast.description}
temp = {this.state.forecast.temp}
/>
)
}
return (
<View style = {styles.container}>
<Text style = {styles.welcome}>
Please Input {this.state.zip}
</Text>
<TextInput
style = {styles.input}
onSubmitEditing={this._handleTextChange}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#666666',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
input: {
fontSize: 20,
borderWidth: 2,
padding: 2,
height: 40,
width: 100,
textAlign: 'center'
},
});
export default WeatherApp;
this is my forecast.js that is suppose to render the forecast after the state is set.
import React, { Component } from "react";
import { StyleSheet, Text, View } from "react-native";
// component renders forecast based on zip code
class Forecast extends Component {
render(){
return(
<View style = {styles.container}>
<Text style = {styles.bigText}>
{this.props.main}
</Text>
<Text style = {styles.mainText}>
Current condition:
{this.props.description}
</Text>
<Text style = {styles.bigText}>
{this.props.temp}
</Text>
</View>
);
}
};
const styles = StyleSheet.create({
container: { height: 130 },
bigText: {
flex: 2,
fontSize: 20,
textAlign: "center",
margin: 10,
color: "#FFFFFF"
},
mainText: {
flex: 1,
fontSize: 16,
textAlign: "center",
color: "#FFFFFF"
}
});
export default Forecast;
in the react-devtools I do not even see the component render or show. Is this the result of styling from not using flexbox properly?
You declare content to be a Forecast component, but never actually reference it in your render().

Categories

Resources