Using dynamic styles in react native - react-native

I've a couple of buttons in my react native app, on pressing any button, color should change. Code is as given below
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
TouchableHighlight,
Image,
Alert
} from 'react-native';
export default class Home extends Component {
constructor(props) {
super(props);
this.state= {
clicks: 0,
show: true,
isbuttonpress: false
};
}
onButtonState = () => {
this.setState({isbuttonpress: true});
}
render() {
return (
<View style={ [styles.container] }>
<Text style= { [styles.header] }>How likely is it that you would recommend this company to a friend or colleague?</Text>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>0</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>1</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>2</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>3</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>4</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.buttonContainer, this.state.isbuttonpress?styles.gobackred:styles.goback] } onPress = { () => this.onButtonState() }>
<Text style = { styles.gobacktext }>5</Text>
</TouchableHighlight>
<TouchableHighlight style = { [styles.nextContainer, styles.goback] } onPress = { () => this.onNextButtonState() }>
<Text style = { styles.gobacktext }>Next</Text>
</TouchableHighlight>
</View>
);
}
}
const styles = StyleSheet.create({
header: {
fontSize: 20,
alignItems: 'center',
padding: 20,
},
container: {
alignItems: 'center',
justifyContent: 'center'
},
buttonContainer: {
height:45,
justifyContent: 'center',
alignItems: 'center',
marginBottom:20,
width:45,
}, gobackred: {
backgroundColor: "#00a2b2",
},
goback: {
backgroundColor: "#00b5ec",
},
gobacktext: {
color: 'white',
},
nextContainer: {
height:45,
marginTop: 15,
justifyContent: 'center',
alignItems: 'center',
marginBottom:20,
width:250,
borderRadius:30,
}
})
Layout is as given below:
Whenever any option is selected, color of that button should change. But in my code, color of all buttons changes when clicked on any button. How can I fix it?

This happens because you used one state this.state.isbuttonpress for all button try to make the component of this code.
your TouchableHighlight Component
DemoButton.js
import React, { Component } from "react";
import { View, Text, TouchableHighlight } from "react-native";
export default class DemoButton extends Component {
constructor(props) {
super(props);
this.state = { isbuttonpress: false };
}
onButtonState = () => {
this.setState({ isbuttonpress: !this.state.isbuttonpress });
};
render() {
return (
<View>
<TouchableHighlight
style={{ backgroundColor: this.state.isbuttonpress ? "red" : "blue" }}
onPress={this.onButtonState}
>
<Text>{this.props.buttonTitle}</Text>
</TouchableHighlight>
</View>
);
}
}
App.js
import DemoButton from "./DemoButton";
export default class Heal extends Component {
constructor(props) {
super(props);
this.state = { isbuttonpress: false };
}
render() {
return (
<View>
<Header />
<DemoButton buttonTitle="0"/>
<DemoButton buttonTitle="1"/>
<DemoButton buttonTitle="2"/>
<DemoButton buttonTitle="3"/>
<DemoButton buttonTitle="4"/>
<DemoButton buttonTitle="5"/>
</View>
)
}
}

Related

How to change only the active button background color [React-Native]

import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
class App extends Component {
constructor(props){
super(props)
this.state={
selected:null
}
}
handle=()=>{
this.setState({selected:1})
}
render() {
return (
<View>
<TouchableOpacity style={[styles.Btn, {backgroundColor:this.state.selected===1?"green":"white"}]} onPress={this.handle}>
<Text style={styles.BtnText}>Button 1</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 2</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 3</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
Btn: {
borderWidth: 1,
width: 100,
height: 20,
borderRadius: 8,
margin: 5,
padding: 10,
justifyContent: 'center',
flexDirection: 'row',
alignItems: 'center',
},
BtnText: {
fontSize: 15,
},
});
export default App;
Snack Link : https://snack.expo.dev/U_fX-6Tao-
I want to make it so when I click a button, the active button backgroundColor should change to "green" and text to "white" and the rest of the buttons backgroundColor and textColor should stay "red". But when I click another button then that button should become active and the previous active button should get back to its normal state.
It would be wonderful if you could also explain the logic behind it as I'm a newbie in React Native.
Thank you.
You are always setting the active button to the first one. Also, I would use an array to render the buttons. I would do something like this:
class App extends Component {
constructor(props){
super(props)
this.state = {
selected: null
}
}
handlePress = (item) => {
this.setState({ selected: item })
}
render() {
return (
<View>
{[...Array(3).keys()].map((item) => {
return (
<TouchableOpacity key={item} style={[styles.Btn, {backgroundColor: this.state.selected === item ? "green" : "white" }]} onPress={() => this.handlePress(item)}>
<Text style={styles.BtnText}>Button {item + 1}</Text>
</TouchableOpacity>
)
})}
</View>
);
}
}
I created an Themed component(OK I did not create it. It is there when I create the app with Expo).
import { useState } from 'react';
import { TouchableOpacity as DefaultTouchableOpacity } from 'react-native';
export type TouchableProps = DefaultTouchableOpacity['props'] & { activeBgColor?: string };
export function TouchableOpacity(props: TouchableProps) {
const [active, setActive] = useState(false);
const { style, activeBgColor, ...otherProps } = props;
if (activeBgColor) {
return (
<DefaultTouchableOpacity
style={[style, active ? { backgroundColor: activeBgColor } : {}]}
activeOpacity={0.8}
onPressIn={() => setActive(true)}
onPressOut={() => setActive(false)}
{...otherProps}
/>
);
}
return <DefaultTouchableOpacity style={style} activeOpacity={0.8} {...otherProps} />;
}
Then I use this TouchableOpacity everywhere.
<TouchableOpacity
style={tw`rounded-sm h-10 px-2 justify-center items-center w-1/5 bg-sky-400`}
activeBgColor={tw.color('bg-sky-600')}
>
<Text style={tw`text-white font-bold`}>a Button</Text>
</TouchableOpacity>
Oh I am writing TailwindCSS with twrnc by the way. You will love it.
See the screenshot below.

Results do not update after a change of state

I have a problem, when I do a search, I get the data from my API, the first time I do a search, everything is fine, all the data is displayed. However, when I do a second search immediately, nothing is updated.
I put in console.log, and I see that I'm getting this data back, yet the display is not updated.
import React, { Component } from "react";
import { SafeAreaView, StyleSheet } from "react-native";
import Search from "./Component/Search";
export default class App extends Component {
render() {
return (
<SafeAreaView style={styles.container}>
<Search />
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
import React from "react";
import { View, TextInput, Button, FlatList, StyleSheet } from "react-native";
import LivreItem from "../Component/LivreItem";
class Search extends React.Component {
constructor(props) {
super(props);
this.inputValue = "";
this.state = { livres: [] };
}
searchBooks = async () => {
const key = "&key=XXXXXXXXXXXXXXXXXXXXXXX";
const url = "https://www.googleapis.com/books/v1/volumes?q=" + this.inputValue + key;
return fetch(url)
.then(response => response.json())
.catch(e => {
console.log("Une erreur s'est produite");
console.log(e);
});
};
getBooks = () => {
if (this.inputValue.length > 0) {
this.searchBooks()
.then(data => this.setState({ livres: data.items }))
.catch(reject => console.log(reject));
}
};
changeText = text => {
this.inputValue = text;
};
render() {
return (
<View style={styles.header_container}>
<View style={styles.sub_container}>
<TextInput
onChangeText={text => this.changeText(text)}
style={styles.input}
placeholder="Ex: Harry Potter"
/>
<Button
style={styles.button}
title="Rechercher"
onPress={() => this.getBooks()}
/>
</View>
<FlatList
style={styles.list}
data={this.state.livres}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <LivreItem livre={item.volumeInfo} />}
/>
</View>
);
}
}
const styles = StyleSheet.create({
sub_container: {
justifyContent: "space-between",
flexDirection: "row",
marginTop: 30,
paddingRight: 10,
paddingLeft: 10
},
header_container: {
flex: 1,
flexDirection: "column",
padding: 10
},
input: {
borderRadius: 4,
borderWidth: 0.5,
borderColor: "#d6d7da",
width: 150,
paddingLeft: 5
},
button: {
borderRadius: 4
},
list: {
paddingLeft: 15,
paddingRight: 15
}
});
export default Search;
import React from "react";
import { View, StyleSheet, Image, Text } from "react-native";
class LivreItem extends React.Component {
constructor(props) {
super(props);
this.state = { livre: this.props.livre};
this.description =
this.state.livre.description === null || this.state.livre.description === undefined
? "Pas de description disponible"
: this.state.livre.description;
this.img = this.state.livre.imageLinks;
this.image =
this.img === undefined ||
this.img.smallThumbnail === undefined ||
this.img.smallThumbnail === null
? null
: this.state.livre.imageLinks.smallThumbnail;
}
render() {
return (
<View style={styles.content}>
<View>
<Image style={styles.image} source={{ uri: this.image }} />
<Image style={styles.image} source={this.image} />
</View>
<View style={styles.content_container}>
<Text style={styles.titre}>{this.state.livre.title}</Text>
<Text style={styles.description} numberOfLines={4}>
{this.description}
</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
content: {
height: 125,
flexDirection: "row",
marginTop: 15
},
content_container: {
flexDirection: "column",
flexShrink: 1,
marginLeft: 10
},
image: {
width: 100,
height: 100
},
titre: {
fontWeight: "bold",
flexWrap: "wrap"
},
description: {
flexWrap: "wrap"
}
});
export default LivreItem;
Thanks.
Configure the prop extraData in Flatlist component ala:
<FlatList
extraData={this.state.livres}
/>
Pass a boolean value to the FlatList extraData.
<FlatList
extraData={this.state.refresh}
/>

Add a button on top of keyboard when called

Im trying to see if I can add a button on top of the keyboard when its called i've seen this feature in many apps but not sure if its possible on expo and react-native. the button should appear with the keyboard and become invisible when the pressed or the keyboard goes away. Ive put a my sample class that goes with the added image
import React, {Component} from 'react';
import {
StyleSheet,
View,
TextInput
} from 'react-native';
export default class test extends Component {
constructor(props) {
super(props);
this.state = {
a: props.navigation,
b: '',
}
}
componentWillMount() {
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{marginTop: 300,marginLeft: 50,borderWidth: 1}}
placeholder="type"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22,
backgroundColor: '#42444f',
},
});
try this approach
constructor(props)
{
super(props)
this.state = {
buttonVisible: false // add this state. this state is the flag for button appearance
}
}
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
}
_keyboardDidShow = () => {
this.setState({
buttonVisible: true
})
}
_keyboardDidHide = () => {
this.setState({
buttonVisible: false
})
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 4 }}>
<TextInput
style={{marginTop: 300,marginLeft: 50,borderWidth: 1}}
placeholder="type"
/>
</View>
<View style={{ flex: 1 }}>
{this.state.buttonVisible ? <TouchableOpacity style={{ flex: 1, backgroundColor: 'red', justifyContent: 'center', alignItems: 'center' }}><Text>Button</Text></TouchableOpacity> : <View/>}
</View>
</View>
);
}
the button will be visible depending on the buttonVisible state value, the state changed inside the keyboard event listener that initialized in componentDidMount

React Native - How to use a ref to set focus to an input when clicking on text

Here's what I'm doing:
export default class myComponent extends Component {
render() {
return (
<View>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<Input ref={input => { this.input = input}}/>
</View>
)
}
}
I am using native-base components... not sure if that is affecting this.
When I press the Text component, I get an error stating: _this2.input.focus is not a function. (In '_this2.input.focus()', '_this2.input.focus' is undefined)
I don't use native-base, but at normal it should be like this:
import * as React from 'react';
import { Text, View, StyleSheet, TextInput, Dimensions } from 'react-native';
import { Constants } from 'expo';
const { width, height } = Dimensions.get('window');
export default class App extends React.Component {
render() {
return (
<View style={styles.container}>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<TextInput style={styles.input} ref={input => { this.input = input}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
input: {
backgroundColor: '#bbb',
width: width - 40,
height: 40,
paddingHorizontal: 10,
paddingVertical: 5,
}
});
You can see the snacks here: https://snack.expo.io/#gasparteixeira/inputfocus
In case anyone comes across this stack overflow during the Hooks Era of React and React Native.
Solution with Hooks following the React Docs https://reactjs.org/docs/hooks-reference.html#useref
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
export default class myComponent extends Component {
public textInput: TextInput | null = null;
render() {
return (
<View>
<Text onPress={() => {this.textInput.focus()}}>Click Me</Text>
<TextInput ref={input => (this.textInput = input as any)}/>
</View>
);
}
}
export default class myComponent extends Component {
render() {
return (
<View>
<Text onPress={() => {this.input.focus()}}>Click Me</Text>
<Input ref={ref => (this.textinput= ref)}/>
</View>
)
}
}
and use this:
handleTextInput = () => {
this.textinput....
};

react native ref not working in dynamic adding rows

I am creating spreadsheet in react native and i want to append columns if we click on add button, but when i used ref in dynamic cols it gives error. here is my code .. please tell me how i can use ref so it will not give me error. following is the error that i receive when i use ref ..
import React, { Component } from 'react';
import {
StyleSheet,
View,
TouchableOpacity,
Text,
TextInput,
ScrollView
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
var unique=1;
export default class Sheet extends Component {
constructor(props) {
super(props);
this.state = {
currentRowNo:1,
serialNo:1,
rows:this.props.species.length,
breaker:true,
appendRows:[],
index:1
}
}
rendercol(rowNo)
{
const col=[];
var serialNo=this.state.index;
col.push(<View key="rowNum" style={styles.column}><View style={[styles.fixCellWidth,{backgroundColor:"#f2f2f2"}]}><Text style={{fontSize:20}}>{rowNo}</Text></View></View>);
for (var j=serialNo;j<=this.state.rows+serialNo-1;j++)
{
col.push(<TouchableOpacity style={styles.fixCellWidth} key={"key_"+j}><Text style={{fontSize:16}} onPress={this.changeValue.bind(this,j)} ref={"red"+j}>{console.log(this.props.action.bind(this,j))}</Text></TouchableOpacity>);
}
return <View key={"Row"+rowNo}>{col}</View>;
}
changeValue(val)
{
this.props.changeVal(val);
}
addRow(){
this.state.appendRows.push(
this.rendercol(this.state.index)
)
this.setState({
index: this.state.index + 1,
appendRows: this.state.appendRows
})
}
render()
{
var _scrollView: ScrollView;
const row=[];
const sheet=[];
sheet.push(<View key="headRow" style={styles.column}><View style={[styles.fixCellWidth,{backgroundColor:"#f2f2f2"}]}><Text style={{fontSize:20}}>S./#</Text></View></View>);
this.props.species.map((option) => {
sheet.push(<View key={option.code} style={styles.column}><View style={[styles.fixCellWidth,{backgroundColor:"#f2f2f2"}]}><Text style={{fontSize:20}}>{option.code}</Text></View></View>);
});
sheet.push(<TouchableOpacity key="rowAdd" style={styles.column} onPress={this.addRow.bind(this)}><View style={[styles.fixCellWidth,{backgroundColor:"green"}]}><Icon name="plus" style={[styles.icon,styles.fontWhite]}/></View></TouchableOpacity>);
return (
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
automaticallyAdjustContentInsets={false}
horizontal={false}
style={{height:650,paddingBottom:10}}>
<View style={styles.column}>
<View>{sheet}</View>
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }}
automaticallyAdjustContentInsets={false}
horizontal={true}
style={[styles.scrollFull]}>
{this.state.appendRows}
</ScrollView>
</View>
</ScrollView>
);
}
}
You are repeating ref assignation in your render function:
return (
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }} // <- here
automaticallyAdjustContentInsets={false}
horizontal={false}
style={{height:650,paddingBottom:10}}>
<View style={styles.column}>
<View>{sheet}</View>
<ScrollView
ref={(scrollView) => { _scrollView = scrollView; }} // <- here
automaticallyAdjustContentInsets={false}
horizontal={true}
style={[styles.scrollFull]}>
{this.state.appendRows}
</ScrollView>
</View>
</ScrollView>
);
But that is not the problem. The problem is that you are creating refs outside render method of the component, to be specific in your rendercol function. Here is the error explanation: https://gist.github.com/jimfb/4faa6cbfb1ef476bd105.
You can add rows using state, look at this approach: Append TextInput component one after another when press button in React Native
import React, { Component } from 'react';
import { View, Text, Platform, StyleSheet, TouchableOpacity,TouchableHighlight, Animated, ScrollView, Image } from 'react-native';
let index = 0
export default class App extends Component {
constructor(context) {
super(context);
this.state = {
rows: []
}
}
_addRow(){
this.state.rows.push(index++)
this.setState({ rows: this.state.rows })
}
render() {
let CheckIndex = i => {
if((i % 2) == 0) {
return styles.gray
}
}
let rows = this.state.rows.map((r, i) => {
return <View key={ i } style={[styles.row, CheckIndex(i)]}>
<Text >Row { r }, Index { i }</Text>
</View>
})
return (
<View style={styles.container}>
<TouchableHighlight onPress={ () => this._addRow() } style={styles.button}>
<Text>Add new row</Text>
</TouchableHighlight>
{ rows }
</View>
);
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 60,
},
gray: {
backgroundColor: '#efefef'
},
row: {
height:40,
alignItems: 'center',
justifyContent: 'center',
borderBottomColor: '#ededed',
borderBottomWidth: 1
},
button: {
alignItems: 'center',
justifyContent: 'center',
height:55,
backgroundColor: '#ededed',
marginBottom:10
}
});