How do you use checkbox in map function in React Native? - react-native

My current code is like this.
export default class All extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
checkedItems: new Map(),
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(id) {
this.setState((prevState) => ({ checkedItems: prevState.checkedItems.set(id, true) }));
console.log(this.state.checkedItems);
}
async componentDidMount() {
const items = ...;
this.setState({ items });
}
render() {
const { items } = this.state;
return (
<Container>
<Content>
<View>
{items.map((item) => (
<View key={item.id}>
<Text>{item.name}</Text>
<View>
<CheckBox
checked={this.state.checkedItems.get(item.id)}
onPress={() => this.handleChange(item.id)}
/>
</View>
</View>
))}
</View>
</Content>
</Container>
);
}
}
I would like to know how to uncheck.
Also, when I firstly check, console.log() in handleChange() outputs Map {}.
Is it correct?
Or if you know better way bay to use checkbox in map function, plz tell me.
I would appreciate it if you could give me advices.

Related

React Native reusable edit component

I'm trying to create a reusable component in react native. The idea is to have only one component responsible to edit all the fields that I have.
Main Component
...
constructor(props) {
super(props);
this.state.FirstName = 'Joe'
}
...
const { FirstName } = this.state.FirstName;
<TouchableOpacity
onPress={() =>
NavigationService.navigate('EditData', {
label: 'First Name',
initialValue: FirstName,
onSubmit: (FirstName) => this.setState({ FirstName })
})
}
>
<CardItem>
<Left>
<FontAwesome5 name="user-edit" />
<Text>First Name</Text>
</Left>
<Right>
<Row>
<Text style={styles.valueText}>{FirstName} </Text>
<Icon name="arrow-forward" />
</Row>
</Right>
</CardItem>
</TouchableOpacity>
// Keep doing the same for other fields
Then, the edit component should be reusable.
constructor(props) {
super(props);
// callback function
this.onSubmit = props.navigation.getParam('onSubmit');
// label/value
this.state = {
label: props.navigation.getParam('label'),
value: props.navigation.getParam('initialValue')
};
}
render() {
const { onSubmit } = this;
const { label, value } = this.state;
return (
<Container>
<Header />
<Content>
<Item floatingLabel style={{ marginTop: 10 }}>
<Label>{label}</Label>
<Input
value={value}
onChangeText={val => this.setState({ value: val })}
/>
</Item>
<Button
onPress={() => {
onSubmit(value);
NavigationService.navigate('TenantDetails');
}
}
>
<Text>OK</Text>
</Button>
</Content>
</Container>
);
}
When back to the main component, the first name value was not changed.
My NavigationService in case it might be the problem:
import { NavigationActions } from 'react-navigation';
let _navigator;
function setTopLevelNavigator(navigatorRef) {
_navigator = navigatorRef;
}
function navigate(routeName, params) {
_navigator.dispatch(
NavigationActions.navigate({
routeName,
params,
})
);
}
// add other navigation functions that you need and export them
export default {
navigate,
setTopLevelNavigator,
};
Thanks
You could pass a callback to your new component which handles this. The new component would start with a state with the initialValue set. It looks like you might be using react-navigation so I would recommend that if you want this component on its own screen you could do
this.navigation.navigate('SetValueScreen', {
initialValue: this.state.email,
onSubmit: (email) => this.setState({ email })
})
and on the SetValueScreen get the initialValue in the constructor and in the render use the callback
class SetValueScreen extends React.PureComponent{
constructor(props){
super(props)
this.onSubmit = props.navigation.getParam('onSubmit');
this.state = {
value: props.navigation.getParam('initialValue')
}
}
render(){
const { onSubmit } = this
const { value } = this.state
return (
...
<Right>
<TextInput value={value} onChangeText={(value) => setState({ value })} />
</Right>
<Button onPress={() => {
onSubmit(value)
navigation.goBack()
}} >
OK
</Button>
...
)
}
}
I hope this helps.

search filter with ListView reactNative

hii i'm still new to react-native i'm trying to implement a search in the listview without Refetching the data (search by name )
like searching the json file i first fetched so
how can i make it works guys ? i followed many tutorials but still can't do it the listView is allways empty
here's my code i hope i found a solution for that
import React, { Component } from "react";
import { View, Text, Image, ListView } from "react-native";
import axios from "axios";
import { SearchButton } from "./utilities/SearchButton";
import SearchBar from "react-native-searchbar";
class SearchScreen extends Component {
constructor(props) {
super(props);
this.ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
this.state = {
doctors: [],
specefic: []
};
}
componentWillMount() {
this.fetchdata();
}
fetchdata = () => {
axios
.get("http://localhost:3000/api/Doctor")
.then(response => this.setState({ doctors: response.data }));
};
static navigationOptions = ({ navigation }) => {
return {
headerRight: <SearchButton navigation={navigation} />
};
};
render() {
return (
<View>
<View>
<SearchBar
ref={ref => (this.props.navigation.searchBar = ref)}
data={this.state.doctors}
handleResults={results => {
this.setState({ specefic: results });
}}
iOSPadding={false}
allDataOnEmptySearch={true}
fontSize={23}
hideBack={true}
heightAdjust={-5}
/>
</View>
<View>
<ListView
enableEmptySections={true}
dataSource={this.ds.cloneWithRows(this.state.doctors)}
renderRow={service => {
return (
<View style={styles.box}>
<Image
style={styles.image}
source={{ uri: service.profileImageUrl }}
/>
<View style={styles.boxContent}>
<Text style={styles.title}>{service.nom}</Text>
<Text style={styles.description}>{service.email}</Text>
</View>
</View>
);
}}
/>
</View>
</View>
);
}
}
export default SearchScreen;

onChangeText setState only sets one character not the whole string

I accept text input from a search bar and setState to text but its only one character at a time how can I continue to update and add to the state rather than replace what's in state? I feel like this is the intended action but my code does not do this.
class FindRecipesScreen extends Component {
static navigationOptions = {
title: "Find Recipes",
header: null
};
constructor(props) {
super(props);
this.state = {
search: "",
recipe: "",
text: "",
};
}
backToHomePage = () => {
this.props.navigation.navigate("Home");
};
componentDidMount() {
this.props.getRecipeList(this.props.auth.jwt);
}
handleSearch = text => {
console.log("text", text);
this.setState({text: text});
};
render() {
return (
<View style={styles.recipe}>
<View style={styles.recipeBar}>
<ActionNavbar title="Find Recipes"
leftAction={this.backToHomePage}
leftIcon={require("app/assets/icons/cancel.png")}
rightAction={this.backToHomePage}
rightIcon={require("app/assets/icons/filter.png")}/>
</View>
<View>
<View>
<SearchBar
containerStyle={styles.searchContainer}
inputContainerStyle={styles.searchInputContainer}
inputStyle={styles.searchInput}
lightTheme
searchIcon={searchIcon}
round
onChangeText={this.handleSearch}
placeholder="Search Cookbooks"
/>
<View style={styles.forward}>
<Image
style={styles.forwardIcon}
width={18}
height={18}
source={require("app/assets/icons/forward.png")}
/>
</View>
</View>
</View>
</View>
);
}
}
I found the solution... I needed const { search } = this.state; after render but before return with searcher
Use debouncer in the handleSearch function so the state is set after your debounce time.

Shoutem fetch data not displaying

First I want to start by saying I am a total noob at React Native and Shoutem. I am not sure if I should write Shoutem or React Native in the subject of my questions, but here is my problem.
I have two screens:
Screen1.js
Screen2.js
Screen1 displays a list of items returned from a fetch. Once I click on the item, it will open the second screen which is the details screen.
I am passing data from screen1 to screen2. In screen2 I need to make another fetch call for different data, but it does not work. I am doing exactly the same thing on both screens.
Here is my code for Screen1:
import React, {
Component
} from 'react';
import {
ActivityIndicator,
TouchableOpacity
} from 'react-native';
import {
View,
ListView,
Text,
Image,
Tile,
Title,
Subtitle,
Overlay,
Screen
} from '#shoutem/ui';
import {
NavigationBar
} from '#shoutem/ui/navigation';
import {
navigateTo
} from '#shoutem/core/navigation';
import {
ext
} from '../extension';
import {
connect
} from 'react-redux';
export class List extends Component {
constructor(props) {
super(props);
this.renderRow = this.renderRow.bind(this);
this.state = {
isLoading: true,
content: null,
}
}
componentDidMount() {
return fetch('https://www.cannabisreports.com/api/v1.0/strains').then((response) => response.json()).then((responseData) => {
this.setState({
isLoading: false,
content: responseData
});
}).done();
}
renderRow(rowData) {
const { navigateTo } = this.props;
return (
//<Text>{rowData.name}, {rowData.createdAt.datetime}</Text>
<TouchableOpacity onPress={() => navigateTo({
screen: ext('Strain'),
props: { rowData }
})}>
<Image styleName="large-banner" source={{ uri: rowData.image &&
rowData.image ? rowData.image : undefined }}>
<Tile>
<Title>{rowData.name}</Title>
<Subtitle>none</Subtitle>
</Tile>
</Image>
</TouchableOpacity>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{flex: 1, paddingTop: 20}}>
<ListView
data={this.state.content.data}
renderRow={rowData => this.renderRow(rowData)}
/>
</View>
);
}
}
// connect screen to redux store
export default connect(
undefined,
{ navigateTo }
)(List);
I am passing rowData to Screen2. I then need to make another fetch calling using data from rowData as it is a path parameter needed for the API call in Screen2.
So basically I need to make a fetch call in Screen2 like this:
fetch('https://mywebsite.com/'+rowData.something+'/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
content: responseJson.data
})
})
.catch((error) => {
console.error(error);
});
Here is my code for screen2:
export default class Strain extends Component {
constructor(props) {
super(props);
this.state = {
content: null,
}
}
componentDidMount() {
return fetch('https://mywebsite.com/'+rowData.something+'/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
content: responseJson.data
})
})
.catch((error) => {
console.error(error);
});
}
renderRow(dataContent) {
return (
<Text>{dataContent.name}</Text>
// This does not work either -> <Text>{dataContent}</Text>
);
}
render() {
const { rowData } = this.props; //This is coming from screen1.js
return (
<ScrollView style = {{marginTop:-70}}>
<Image styleName="large-portrait" source={{ uri: rowData.image &&
rowData.image ? rowData.image : undefined }}>
<Tile>
<Title>{rowData.name}</Title>
<Subtitle>{rowData.createdAt.datetime}</Subtitle>
</Tile>
</Image>
<Row>
<Text>Seed Company: {rowData.seedCompany.name}</Text>
</Row>
<Divider styleName="line" />
<Row>
<Icon name="laptop" />
<View styleName="vertical">
<Subtitle>Visit webpage</Subtitle>
<Text>{rowData.url}</Text>
</View>
<Icon name="right-arrow" />
</Row>
<Divider styleName="line" />
<View style={{flex: 1, paddingTop: 20}}>
<ListView
data={content}
renderRow={dataContent => this.renderRow(dataContent)}
/>
</View>
<Divider styleName="line" />
</ScrollView>
);
}
}
My fetch URL returns data like this:
{
data: {
name: "7.5833",
another_name: "8.6000",
different_name: "5.7500",
}
}
This only returns one data object like what you see above.
When I run the code I get this error:
null is not an object (evaluating 'Object.keys(e[t])')
Please let me know if you need me to provide more info.
I have tried so many different things and nothing seems to work so I am in need of some help. What am I doing wrong?
Not sure why this works but it does.
I used a function to fetch my data and then call the function in componentDidMount like this:
getData() {
return fetch('https://mywebsite.com/myotherdata')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
data: responseJson.data
});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.getData();
}
Then to get the values from the JSON response I am doing this:
this.state.data.name
I am having another issue, but I will create another question.

Cards of Native Base dynamically in react native and Firebase

I have data to extract from Firebase and i did. It's displayed perfectly fine in a listview. But now i have to display them in cards from the native base . this is the code i tried https://github.com/GeekyAnts/NativeBase/issues/347 but i get an error : undefined is not an object
import CardItem from'./CardItem'
import {Container, Content, Card, Body, Title} from 'native-base';
export default class SixteenTab extends Component {
constructor(props) {
super(props);
this.itemsRef = this.getRef().child('docs/topics/topics_2016/');
}
componentDidMount() {
// start listening for firebase updates
this.listenForItems(this.itemsRef);
}
getRef() {
return firebaseApp.database().ref();
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
var items = [];
snap.forEach((child) => {
items.push({
title: child.val().title,
_key: child.key
});
});
this.setState({
items: items
});
});
}
render() {
return (
<View>
<Card dataArray={this.state.items}
renderRow={(item) => this._renderItem(item)}>
</Card>
</View>
)
}
_renderItem(item) {
return (
<CardItem item={item}/>
);
}
}
CardItem Page
class CardItem extends Component {
render() {
return (
<View style={styles.listItem}>
<Text style={styles.liText}>{this.props.item.title}</Text>
</View>
);
}
}
That's the code i used but i keep getting an error like the image below --> any idea please
PS: all the items are been extracted from firebase database correctly, since i can see them in the console
After putting this line this.state = { items: [] }; in the constructor, i get this warning
when trying the second method of Irfan , i get this warning and nothing is displayed in the screen
that's the final i wrote and still not working
export default class SixteenTab extends Component {
constructor(props) {
super(props);
this.itemsRef = this.getRef().child('docs/topics/topics_2016/');
this.state = { items: null };
}
componentDidMount() {
this.listenForItems(this.itemsRef);
}
componentWillMount() {
this.setState({
items:[]
});
}
getRef() {
return firebaseApp.database().ref();
}
listenForItems(itemsRef) {
itemsRef.on('value', (snap) => {
var items = [];
snap.forEach((child) => {
items.push({
title: child.val().title,
_key: child.key
});
});
this.setState({
items: items
});
});
}
render() {
return (
<View>
<Content>
<Card>
{
this.state.items.map((item,index)=>{
return (
<CardItem key={index}>
<View>
<Text>{item.title}</Text>
</View>
</CardItem>
)
})
}
</Card>
</Content>
</View>
)
}
_renderItem(item) {
return (
<ListItem item={item}/>
);
}
As per native base doc, dataArray and renderRow is not support Card Component. So should update your render function.
render() {
return (
<Container>
<Content>
<Card>
{
this.state.items.map((item, index)=>{
return (
<CardItem key={index}>
<View>
<Text>{item.title}</Text>
</View>
</CardItem>
)
})
}
</Card>
</Content>
</Container>
)
}
If you want your cards SEPARATELY , you need to put the key attribute in Card, not in CardItem! Like this:
render() {
return (
<Container>
<Content>
{
this.state.items.map((item, index)=>{
return (
<Card key={index}>
<CardItem>
<Text>{item.title}</Text>
</CardItem>
<Card/>
)
})
}
</Content>
</Container>
)
}