Change specific buttons background onPress (React Native) - react-native

I'm trying to build a simple quiz. I would like to change the background of a button to green if it's correct and to red if it's incorrect onPress. My questions is how do I select only ONE of the buttons? Currently I can only get all of the buttons to turn colour.
export default class TestScreen extends React.Component {
constructor(props){
super(props);
this.qno = 0
this.score = 0
const jdata = jsonData.quiz.quiz1
arrnew = Object.keys(jdata).map( function(k) { return jdata[k] });
this.state = {
question : arrnew[this.qno].question,
options : arrnew[this.qno].options,
correctoption : arrnew[this.qno].correctoption,
countCheck : 0,
back_colour: 'gray',
answered: false,
}
}
change_colour(ans) {
if(this.state.answered == false){
if(ans == this.state.correctoption){
Alert.alert('Correct!');
this.setState({ back_colour: 'green'})
}
else {
Alert.alert('Wrong!');
this.setState({ back_colour: 'red'})
}
this.setState({ answered: true })
}
else {
// Do nothing
}
}
render() {
let _this = this
const currentOptions = this.state.options
const options = Object.keys(currentOptions).map( function(k) {
return ( <View key={k} style={{margin:10}}>
<Button color={_this.state.back_colour} onPress={() => _this.change_colour(k)} title={currentOptions[k]} />
</View>)
});
}
}

yeah its great and easy with react . You can use ids for this purpose.
example ..
validateUser = id => {
const newItems = items.map(item => {
if(item.id === id ) {
then check anwer here
and trun status true or false ..
}
})
}
items.map(item function() {
<Button color={item.status ? 'red' : 'black' } onPress={() =>
this.validateAnswer(item.id)}>
})
and your item object in your array should be like this ..
{
id: '0',
status: true/false
}
i think this will help .

Related

How do I clear placeholder text when using a ref in React Native?

I have a TextInput component gets reused in a few different places:
export default class SomeTextInput extends Component {
constructor(props) {
super(props);
}
render() {
let fontWeight = this.props.fontWeight ? this.props.fontWeight : 'Light';
let fontName = this.props.fontName ? this.props.fontName : 'Montserrat';
let fontString = createFontString(fontName, fontWeight);
let applyFontFamily = { fontFamily: fontString };
let style = this.props.style.constructor === Array ? this.props.style : [this.props.style];
return (
<TextInput
ref={(ref) => {
this.textInput = ref
}}
{...this.props}
style={[applyFontFamily, ...style]}
onFocus={() => {
this.clearText();
console.log('show me this.textInput', this.textInput.props.placeholder)
}}
/>
)
}
clearText() {
this.textInput.clear();
console.log('is this being reached???')
}
focus() {
this.textInput.focus();
}
blur() {
this.textInput.blur();
}
}
I've also tried using clearTextOnFocus. I believe the best way to do this would be to change the placeholder to '', but I'm not sure how given that the placeholder text is taken from a prop that's been passed down.
edit: I'm going to add the code that #ravibagul91 suggested
export default class OVTextInput extends Component {
constructor(props) {
super(props);
// this.state = {
// placeholder: props.placeholder
// }
}
render() {
let fontWeight = this.props.fontWeight ? this.props.fontWeight : 'Light';
let fontName = this.props.fontName ? this.props.fontName : 'Montserrat';
let fontString = createFontString(fontName, fontWeight);
let applyFontFamily = { fontFamily: fontString };
let style = this.props.style.constructor === Array ? this.props.style : [this.props.style];
return (
<TextInput
ref={(ref) => {
this.textInput = ref
}}
{...this.props}
style={[applyFontFamily, ...style]}
onFocus={() => {
// this.setState({ placeholder: "" });
this.clearText();
}}
/>
)
}
clearText = () => {
console.log(this.textInput)
console.log('is this being reached???', this.textInput.value);
console.log('is this being reached???', this.textInput.placeholder);
this.textInput.placeholder = "";
this.textInput.value = "";
}
// focus = () => {
// this.textInput.focus();
// }
// blur = () => {
// this.textInput.blur();
// }
focus() {
this.textInput.focus();
}
blur() {
this.textInput.blur();
}
};
What you are currently doing is erasing the value of the text. Your Textinput looks like a prop for receiving and using values. Textinput does not currently have the ability to clear placeholders. If you make a proposal, you can use the status values to solve it.
export default class SomeTextInput extends Component {
constructor(props) {
super(props);
this.state={
placeholder: props.placeholder
}
}
....
<TextInput
ref={(ref) => {
this.textInput = ref
}}
placeholder={this.state.placeholder}
{...this.props}
style={[applyFontFamily, ...style]}
onFocus={() => {
this.setState({ placeholder : "" });
console.log('show me placeholder', this.state.placeholder)
}}
/>
You can directly clear the placeholder like,
this.textInput.placeholder = "";
Demo
Note: This is tested simply on input but same will work for TextInput.

How I can resolve this : Warning: Encountered two children with the same key, `%s`

I am new to react-native and this is not me who program this app.
Could someone help me to fix this error, I think its the flatlist who cause this because it happen only I load the page or search something on the list. I know there is a lot a question about this error but I don't find a solution for me.
Warning: Encountered two children with the same key,%s. Keys should be unique so that components maintain their identity across updates.
ContactScreen.js
import React from 'react';
import { Button, View, FlatList, Alert, StyleSheet, KeyboardAvoidingView } from 'react-native';
import { ListItem, SearchBar } from 'react-native-elements';
import Ionicons from 'react-native-vector-icons/Ionicons';
import { Contacts } from 'expo';
import * as Api from '../rest/api';
import theme from '../styles/theme.style';
import { Contact, ContactType } from '../models/Contact';
class ContactsScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle: "Contacts",
headerRight: (
<Button
onPress={() => navigation.popToTop()}
title="Déconnexion"
/>
),
}
};
constructor(props) {
super(props);
this.state = {
contacts: [],
search: '',
isFetching: false,
display_contacts: []
}
}
async componentDidMount() {
this.getContactsAsync();
}
async getContactsAsync() {
const permission = await Expo.Permissions.askAsync(Expo.Permissions.CONTACTS);
if (permission.status !== 'granted') { return; }
const contacts = await Contacts.getContactsAsync({
fields: [
Contacts.PHONE_NUMBERS,
Contacts.EMAILS,
Contacts.IMAGE
],
pageSize: 100,
pageOffset: 0,
});
const listContacts = [];
if (contacts.total > 0) {
for(var i in contacts.data) {
let contact = contacts.data[i];
let id = contact.id;
let first_name = contact.firstName;
let middle_name = contact.middleName;
let last_name = contact.lastName;
let email = "";
if ("emails" in contact && contact.emails.length > 0) {
email = contact.emails[0].email;
}
let phone = "";
if ("phoneNumbers" in contact && contact.phoneNumbers.length > 0) {
phone = contact.phoneNumbers[0].number;
}
listContacts.push(new Contact(id, first_name, middle_name, last_name, email, phone, ContactType.UP));
}
}
const soemanContacts = await Api.getContacts();
if (soemanContacts.length > 0) {
for(var i in soemanContacts) {
let contact = soemanContacts[i];
let id = contact.contact_id.toString();
let first_name = contact.contact_first_name
let last_name = contact.contact_last_name;
let email = contact.contact_email;
let phone = contact.contact_phone.toString();
listContacts.push(new Contact(id, first_name, "", last_name, email, phone, ContactType.DOWN));
}
}
listContacts.sort((a, b) => a.name.localeCompare(b.name));
this.setState({contacts: listContacts});
this.setState({ isFetching: false });
this.updateSearch(null);
}
async addContactAsync(c) {
const contact = {
[Contacts.Fields.FirstName]: c.firstName,
[Contacts.Fields.LastName]: c.lastName,
[Contacts.Fields.phoneNumbers]: [
{
'number': c.phone
},
],
[Contacts.Fields.Emails]: [
{
'email': c.email
}
]
}
const contactId = await Contacts.addContactAsync(contact);
}
onRefresh() {
this.setState({ isFetching: true }, function() { this.getContactsAsync() });
}
updateSearch = search => {
this.setState({ search });
if(!search) {
this.setState({display_contacts: this.state.contacts});
}
else {
const res = this.state.contacts.filter(contact => contact.name.toLowerCase().includes(search.toLowerCase()));
console.log(res);
this.setState({display_contacts: res});
console.log("contact display "+ this.state.display_contacts);
}
};
toggleContact(contact) {
switch(contact.type) {
case ContactType.SYNC:
break;
case ContactType.DOWN:
this.addContactAsync(contact);
break;
case ContactType.UP:
Api.addContact(contact);
break;
}
/*Alert.alert(
'Synchronisé',
contact.name + 'est déjà synchronisé'
);*/
}
renderSeparator = () => (
<View style={{ height: 0.5, backgroundColor: 'grey', marginLeft: 0 }} />
)
render() {
return (
<View style={{ flex: 1 }}>
<KeyboardAvoidingView style={{ justifyContent: 'flex-end' }} behavior="padding" enabled>
<SearchBar
platform="default"
lightTheme={true}
containerStyle={styles.searchBar}
inputStyle={styles.textInput}
placeholder="Type Here..."
onChangeText={this.updateSearch}
value={this.state.search}
clearIcon
/>
<FlatList
data={this.state.display_contacts}
onRefresh={() => this.onRefresh()}
refreshing={this.state.isFetching}
renderItem={this.renderItem}
keyExtractor={contact => contact.id}
ItemSeparatorComponent={this.renderSeparator}
ListEmptyComponent={this.renderEmptyContainer()}
/>
</KeyboardAvoidingView>
</View>
);
}
renderItem = (item) => {
const contact = item.item;
let icon_name = '';
let icon_color = 'black';
switch(contact.type) {
case ContactType.SYNC:
icon_name = 'ios-done-all';
icon_color = 'green';
break;
case ContactType.DOWN:
icon_name = 'ios-arrow-down';
break;
case ContactType.UP:
icon_name = 'ios-arrow-up';
break;
}
return (
<ListItem
onPress={ () => this.toggleContact(contact) }
roundAvatar
title={contact.name}
subtitle={contact.phone}
//avatar={{ uri: item.avatar }}
containerStyle={{ borderBottomWidth: 0 }}
rightIcon={<Ionicons name={icon_name} size={20} color={icon_color}/>}
/>
);
}
renderEmptyContainer() {
return (
<View>
</View>
)
}
}
const styles = StyleSheet.create({
searchBar: {
backgroundColor: theme.PRIMARY_COLOR
},
textInput: {
backgroundColor: theme.PRIMARY_COLOR,
color: 'white'
}
});
export default ContactsScreen;
I use react-native and expo for this application.
Just do this in you flatlist
keyExtractor={(item, index) => String(index)}
I think that your some of contact.id's are same. So you can get this warning. If you set the index number of the list in FlatList, you can't show this.
keyExtractor={(contact, index) => String(index)}
Don't build keys using the index on the fly. If you want to build keys, you should do it BEFORE render if possible.
If your contacts have a guaranteed unique id, you should use that. If they do not, you should build a key before your data is in the view using a function that produces unique keys
Example code:
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
const keyGenerator = () => '_' + Math.random().toString(36).substr(2, 9)
// in component
key={contact.key}
Just do this in your Flatlist
keyExtractor={(id) => { id.toString(); }}
I got same error and I fixed in this case:
do not code in this way (using async) - this will repeat render many times per item (I don't know why)
Stub_Func = async () => {
const status = await Ask_Permission(...);
if(status) {
const result = await Get_Result(...);
this.setState({data: result});
}
}
componentDidMount() {
this.Stub_Func();
}
try something like this (using then):
Stub_Func = () => {
Ask_Permission(...).then(status=> {
if(status) {
Get_Result(...).then(result=> {
this.setState({data:result});
}).catch(err => {
throw(err);
});
}
}).catch(err => {
throw(err)
});
}
componentDidMount() {
this.Stub_Func();
}

How to make dynamic checkbox in react native

I am making a react native application in which i need to make checkbox during runtime.I means that from server i will get the json object which will have id and label for checkbox.Now i want to know that after fetching data from server how can i make checkbox also how can i handle the checkbox , i mean that how many number of checkbox will be there it will not be static so how can i declare state variables which can handle the checkbox.Also how can i handle the onPress event of checkbox.Please provide me some help of code .Thanks in advance
The concept will be using an array in the state and setting the state array with the data you got from the service response, Checkbox is not available in both platforms so you will have to use react-native-elements. And you can use the map function to render the checkboxes from the array, and have an onPress to change the state accordingly. The code will be as below. You will have to think about maintaining the checked value in the state as well.
import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-elements';
export default class Sample extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, key: 'test1', checked: false },
{ id: 2, key: 'test1', checked: true }
]
};
}
onCheckChanged(id) {
const data = this.state.data;
const index = data.findIndex(x => x.id === id);
data[index].checked = !data[index].checked;
this.setState(data);
}
render() {
return (<View>
{
this.state.data.map((item,key) => <CheckBox title={item.key} key={key} checked={item.checked} onPress={()=>this.onCheckChanged(item.id)}/>)
}
</View>)
}
}
Here's an example how you can do this. You can play with the code, to understand more how it's working.
export default class App extends React.Component {
state = {
checkboxes: [],
};
async componentDidMount() {
// mocking a datafetch
setTimeout(() => {
// mock data
const data = [{ id: 1, label: 'first' }, { id: 2, label: 'second' }];
this.setState({
checkboxes: data.map(x => {
x['value'] = false;
return x;
}),
});
}, 1000);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{JSON.stringify(this.state)}
</Text>
{this.state.checkboxes.length > 0 &&
this.state.checkboxes.map(checkbox => (
<View>
<Text>{checkbox.label}</Text>
<CheckBox
onValueChange={value =>
this.setState(state => {
const index = state.checkboxes.findIndex(
x => x.id === checkbox.id
);
return {
checkboxes: [
...state.checkboxes.slice(0, index),
{ id: checkbox.id, label: checkbox.label, value },
...state.checkboxes.slice(index+1),
],
};
})
}
value={checkbox.value}
key={checkbox.id}
/>
</View>
))}
</View>
);
}
}

React-Native pass Textinputvalue to other js

i'm a very newbie to react-native, so sry for this kind of question.
I have to implement a app with that i can log into our website. More details later.
First problem:
LoginScreen.js
var Animated = require('Animated');
var Dimensions = require('Dimensions');
var Image = require('Image');
var React = require('React');
var StatusBar = require('StatusBar');
var StyleSheet = require('StyleSheet');
var View = require('View');
var {
Text
} = require('OnTrackText');
var LoginButton = require('../common/LoginButton');
var TouchableOpacity = require('TouchableOpacity');
var TextInput = require('TextInput');
var {
skipLogin
} = require('../actions');
var {
connect
} = require('react-redux');
class LoginScreen extends React.Component {
state = {
anim: new Animated.Value(0),
name: '',
password: ''
};
componentDidMount() {
Animated.timing(this.state.anim, {
toValue: 3000,
duration: 3000
}).start();
}
render() {
return ( < Image style = {
styles.container
}
source = {
require('./img/login-background.png')
} >
< StatusBar barStyle = "default" / >
< TouchableOpacity accessibilityLabel = "Skip login"
accessibilityTraits = "button"
style = {
styles.skip
}
onPress = {
() => this.props.dispatch(skipLogin())
} >
< Animated.Image style = {
this.fadeIn(2800)
}
source = {
require('./img/x.png')
}
/>
</TouchableOpacity >
< View style = {
styles.section
} >
< Animated.Image style = {
this.fadeIn(0)
}
source = {
require('./img/ontrack-logo#3x.png')
}
/>
</View >
< View style = {
styles.section
} >
< Animated.Text style = {
[styles.h1, this.fadeIn(700, -20)]
} >
Willkommen zur < /Animated.Text>
<Animated.Text style={[styles.h1, {marginTop: -10}, this.fadeIn(700, 20)]}>
OnTrack App
</Animated.Text >
< /View>
<View style={styles.section}>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({ name: text }) }
value={this.state.name}
placeholder={"Benutzername"}
/ >
< TextInput style = {
styles.input
}
onChangeText = {
(text) => this.setState({
password: text
})
}
value = {
this.state.password
}
secureTextEntry = {
true
}
placeholder = {
"Password"
}
/>
</View >
< Animated.View style = {
[styles.section, styles.last, this.fadeIn(2500, 20)]
} >
< LoginButton name = {
this.state.name
}
password = {
this.state.password
}
source = "First screen" / >
< /Animated.View>
</Image >
);
}
fadeIn(delay, from = 0) {
....
}
const scale = Dimensions.get('window').width / 375;
var styles = StyleSheet.create({
....
}
});
module.exports = connect()(LoginScreen);
As you can see i would like to enter the name and password into the textinput.
Than
the LoginButton.js
'use strict';
const React = require('react');
const {StyleSheet} = require('react-native');
const { logInToWeb } = require('../actions');
const {connect} = require('react-redux');
class LoginButton extends React.Component {
props: {
style: any;
source?: string; // For Analytics
dispatch: (action: any) => Promise;
onLoggedIn: ?() => void;
};
state: {
isLoading: boolean;
};
_isMounted: boolean;
constructor() {
super();
this.state = { isLoading: false };
}
componentDidMount() {
this._isMounted = true;
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
if (this.state.isLoading) {
return (
<OnTrackButton
style={[styles.button, this.props.style]}
caption="Please wait..."
onPress={() => {}}
/>
);
}
return (
<OnTrackButton
style={[styles.button, this.props.style]}
// icon={require('../login/img/f-logo.png')}
caption="Login to OnTrack"
// onPress={this.props.onpress}
onPress={() => this.logIn()}
/>
);
}
async logIn() {
const {dispatch, onLoggedIn, name, password} = this.props;
this.setState({isLoading: true});
try {
await Promise.race([
dispatch(logInToWeb(name,password)),
timeout(15000),
]);
} catch (e) {
const message = e.message || e;
if (message !== 'Timed out' && message !== 'Canceled by user') {
alert(message);
console.warn(e);
}
return;
} finally {
this._isMounted && this.setState({isLoading: false});
}
onLoggedIn && onLoggedIn();
}
}
async function timeout(ms: number): Promise {
return new Promise((resolve, reject) => {
setTimeout(() => reject(new Error('Timed out')), ms);
});
}
var styles = StyleSheet.create({
...
});
module.exports = connect()(LoginButton);
Than
the dispatch(logInToWeb)method in ./action/login.js looks like this:
'use strict';
import type { Action, ThunkAction } from './types';
const Parse = require('parse/react-native');
const {Platform} = require('react-native');
const Alert = require('Alert');
function logInToWeb(data): ThunkAction {
const {name, password} = data
Alert.alert(
`Hi, ${name} & ${password}`,
'möchten Sie sich ausloggen?',
[
{ text: 'Abbruch' },
{ text: 'Ausloggen' },
]
)
}
function skipLogin(): Action {
return {
type: 'SKIPPED_LOGIN',
};
}
function logOut(): ThunkAction {
...
}
function logOutWithPrompt(): ThunkAction {
....
}
module.exports = {logInToWeb, skipLogin, logOut, logOutWithPrompt};
So the Question is:
how can i pass the value of the Textinput from the LoginScreen.js on ButtonClick To the logInToWeb-Method in the login.js
How can i get the name and password in the alert that i called in login.js
Thats it. Later i will ask more about bearer-auth and loggin to server :)
I think what you're asking is how to send the name and password to your logIn() method? Maybe something like this would work:
// Login Button
<LoginButton
name={this.state.name}
password={this.state.password}
source="First screen" />
// Login method
async logIn() {
const {dispatch, onLoggedIn, name, password} = this.props;
this.setState({isLoading: true});
try {
await Promise.race([
dispatch(logInToWebk({name, password})),
timeout(15000),
]);
}
}
then
function logInToWebk(data): ThunkAction {
const { name, password } = data
// do something with name + password
}

react dnd nesting level on hover

I want to implement a drop system where if drop targets are nested you can cycle between them using the mouse scroll wheel (or have an automatic cycle happen after a certain amount of time) this will be particularly useful because many of the nested targets occupy the exact same areas on screen.
I'm presently thinking that I could use a callback passed down from the container that could be used by drop targets to register/de-register themselves when their hover function is called/when isOver prop changes but it's very coupled and I have to pass props into the DropTargets from the container, in the real world application there will be an unknown number of levels between container and drop target so I'd likely have to set up some kind of callback system, overall its not an ideal solution. Also I'm not sure how to ensure the correct order when cycling as the drop targets don't know how deeply nested they are (see code below for how I've implemented this). Is there a cleaner way to implement such a system?
#DragDropContext(HTML5Backend)
export default class Container extends Component {
constructor (props) {
super(props);
this.state = {
bins: []
};
this.status = {};
this._cycle = this.cycle.bind(this);
this._register = this.register.bind(this);
this._deregister = this.deregister.bind(this);
}
componentWillUnmount () {
if (this.timer) {
window.clearInterval(this.timer);
}
}
register (name) {
if (this.state.bins.findIndex(e => e === name) === -1) {
this.setState({
bins: this.state.bins.concat(name)
});
if (!this.timer) {
this.cycledBins = [];
this.timer = window.setInterval(this._cycle, 3000);
this._cycle();
}
}
}
deregister (name) {
if (this.state.bins.findIndex(e => e === name) !== -1) {
const bins = this.state.bins.filter((e) => e === name);
this.setState({
bins
});
if (!bins.length) {
window.clearInterval(this.timer);
this.timer = undefined;
}
}
}
cycle () {
this.status = {};
const bins = this.state.bins;
let activeBin = -1;
for (let i = 0; i < bins.length; i += 1) {
if (this.cycledBins.findIndex(bin => bin === bins[i]) === -1) {
activeBin = bins[i];
break;
}
}
if (activeBin === -1) {
activeBin = bins[0];
this.cycledBins = [];
}
this.cycledBins.push(activeBin);
this.activeBin = activeBin;
this.status[activeBin] = {
isActive: true,
isOnlyActive: bins.length === 1
}
this.forceUpdate();
}
render () {
return (
<div>
bins = {JSON.stringify(this.state.bins)}<br />
cycledBins = {JSON.stringify(this.cycledBins)}
<div style={{ overflow: 'hidden', clear: 'both' }}>
<Dustbin name="Outer" register={this._register} deregister={this._deregister} status={this.status["Outer"]} >
<Dustbin name="Middle" register={this._register} deregister={this._deregister} status={this.status["Middle"]} >
<Dustbin name="Inner" register={this._register} deregister={this._deregister} status={this.status["Inner"]} />
</Dustbin>
</Dustbin>
</div>
<div style={{ overflow: 'hidden', clear: 'both' }}>
<Box name='Glass' />
<Box name='Banana' />
<Box name='Paper' />
</div>
</div>
);
}
}
const boxTarget = {
hover(props) {
props.register(props.name);
}
};
#DNDDropTarget('Box', boxTarget, (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()//,
//canDrop: monitor.canDrop()
}))
export default class Dustbin extends Component {
static propTypes = {
connectDropTarget: PropTypes.func.isRequired,
isOver: PropTypes.bool.isRequired//,
//canDrop: PropTypes.bool.isRequired
};
componentWIllMount () {
if (!this.props.isOver) {
this.props.deregister(this.props.name);
}
}
componentWillReceiveProps (nextProps) {
if (nextProps.isOver !== this.props.isOver && !nextProps.isOver) {
this.props.deregister(this.props.name);
}
}
render() {
const { canDrop, isOver, connectDropTarget, status } = this.props;
const isOnlyActive = status && status.isOnlyActive;
let isActive = status && status.isActive;
if (!isOver && isActive) {
isActive = false;
}
return connectDropTarget(
<div>
<DropTarget position={BEFORE} shown={isActive} />
{ isActive && !isOnlyActive ? '(' + this.props.name + ')' : undefined }
{ this.props.children ? this.props.children : (
<div style={style}>
{ isActive ?
'Release to drop' :
'Drag a box here'
}
</div>
) }
<DropTarget position={AFTER} shown={isActive} />
</div>
);
}
}