I have dataset, which looks like this:
var items = [
{
id: 1,
name: 'foo',
email: 'foo'
},
{
id: 2,
name: 'foo',
email: 'foo'
},
{
id: 3,
name: 'foo',
email: 'foo'
},
];
module.exports = items;
I'm feeding this data to searchable dropdown, so the data will be visible within the dropdown
The dropdown component, looks like this:
<SearchableDropdown
onItemSelect={(item) => {
const items = this.state.selectedItems;
items.push(item)
this.setState({ selectedItems: items });
}}
containerStyle={{ padding: 5 }}
onRemoveItem={(item, index) => {
const items = this.state.selectedItems.filter((sitem) => sitem.id !== item.id);
this.setState({ selectedItems: items });
}}
itemStyle={{
padding: 10,
marginTop: 2,
backgroundColor: '#ddd',
borderColor: '#bbb',
borderWidth: 1,
borderRadius: 5,
}}
itemTextStyle={{ color: '#222' }}
itemsContainerStyle={{ maxHeight: 140 }}
items={items}
defaultIndex={null}
resetValue={false}
textInputProps={
{
placeholder: "Choose priority level",
underlineColorAndroid: "transparent",
style: {
padding: 12,
borderWidth: 1,
borderColor: '#ccc',
borderRadius: 5,
},
onTextChange: text => console.log(text)
}
}
listProps={
{
nestedScrollEnabled: false,
}
}
/>
</Fragment>
And I imported the dataset with the following import:
import items from '../components/items';
However I'm getting that element type is invalid excepted a string but got object, I've tried previous threads from stackoverflow however nothing seems to solve my problem. Perhaps I'm missing something small that my eyes can't pick up? Any help appreciated.
First, you have to export the array as variable like
items.js
export const items = [
...
...
]
import it into your component.js like as
import {items} from '../path/to/items';
Just for confirmation log it inside your render method
console.log('Array Items', item);
Hope this will help you.
Related
I am new to react native. I cannot figure out how to show selected values from dropdown. I have inserted a dropdown in a data table. When I try to select value from any drop down every dropdown showing the same value. Also I an trying to store values in single useState.. I have searched a lot.. Please help me..
Here is expo snack
here is my code -
import React, {Component, useState} from 'react';
import { FlatList,StyleSheet, Text, View } from 'react-native';
import { DataTable } from 'react-native-paper';
import { Dropdown } from 'react-native-element-dropdown';
const optionsPerPage = [2, 3, 4];
const data2 = [
{ label: 'Item 1', value: '1' },
{ label: 'Item 2', value: '2' },
{ label: 'Item 3', value: '3' },
{ label: 'Item 4', value: '4' },
{ label: 'Item 5', value: '5' },
{ label: 'Item 6', value: '6' },
{ label: 'Item 7', value: '7' },
{ label: 'Item 8', value: '8' },
];
const MyComponent = () => {
const data = [...Array(20).keys()];
const [value, setValue] = useState(null);
const [isFocus, setIsFocus] = useState(false);
const [page, setPage] = React.useState(0);
const [itemsPerPage, setItemsPerPage] = React.useState(optionsPerPage[0]);
React.useEffect(() => {
setPage(0);
}, [itemsPerPage]);
const _renderItem = ({ item }) => (
<DataTable.Row>
<DataTable.Cell>{item}</DataTable.Cell>
<DataTable.Cell numeric>159</DataTable.Cell>
<DataTable.Cell >
<Dropdown
style={[styles.dropdown, isFocus && { borderColor: 'blue' }]}
placeholderStyle={styles.placeholderStyle}
selectedTextStyle={styles.selectedTextStyle}
inputSearchStyle={styles.inputSearchStyle}
iconStyle={styles.iconStyle}
data={data2}
search
maxHeight={300}
labelField="label"
valueField="value"
placeholder={!isFocus ? 'Select item' : '...'}
searchPlaceholder="Search..."
value={value}
onFocus={() => setIsFocus(true)}
onBlur={() => setIsFocus(false)}
onChange={item => {
setValue(item.value);
setIsFocus(false);
}}
/>
</DataTable.Cell>
</DataTable.Row>
);
return (
<DataTable>
<DataTable.Header>
<DataTable.Title>Dessert</DataTable.Title>
<DataTable.Title numeric>Calories</DataTable.Title>
<DataTable.Title numeric>Fat</DataTable.Title>
</DataTable.Header>
<FlatList data={data} renderItem={_renderItem} />
</DataTable>
);
};
export default MyComponent;
const styles = StyleSheet.create({
container: {
backgroundColor: 'white',
padding: 16,
},
dropdown: {
height: 50,
width:80,
borderColor: 'gray',
borderWidth: 0.5,
borderRadius: 8,
paddingHorizontal: 8,
marginLeft:20
},
icon: {
marginRight: 5,
},
label: {
position: 'absolute',
backgroundColor: 'white',
left: 22,
top: 8,
zIndex: 999,
paddingHorizontal: 8,
fontSize: 14,
},
placeholderStyle: {
fontSize: 16,
},
selectedTextStyle: {
fontSize: 16,
},
iconStyle: {
width: 20,
height: 20,
},
inputSearchStyle: {
height: 40,
fontSize: 16,
},
});
Tip 1: Unique ID
Whenever iterators are used provide key. In <FlatList/> use keyExtractor prop.
<FlatList
data={data}
extraData={formValue}
renderItem={_renderItem}
keyExtractor={(k) => `${k}`}
/>
Tip 2: Form Value
Every form element should store value as key: value.
// const [value, setValue] = useState(null);
const [formValue, setFormValue] = useState({});
Getter/Setter for form values.
const _getValue = () => {
if (item in formValue) return formValue[item];
return null;
};
const _onChange = (obj) => {
setFormValue((v) => ({ ...v, [item]: obj.value }));
setIsFocusId(null);
};
Tip 3: Focused Value
Since there are various elements better to give each element an ID.
// const [isFocus, setIsFocus] = useState(false);
const [isFocusId, setIsFocusId] = useState(null);
onFocus/onBlur
// onFocus={() => setIsFocus(true)}
// onBlur={() => setIsFocus(false)}
// onFocus={() => setIsFocusId(item)}
// onBlur={() => setIsFocusId(null)}
Solution: https://snack.expo.dev/#fanish/95b120
I am new to react-native. I have a flatlist, that takes data from "state". This works. Then, I added a new function in order to add new data to the flatlist (additionally to the existing data).
As soon as I click on the "delete" button ( don't mind the name) the data of the flatlist is being deleted completely. I want the output to be like
Object 1
Object 2
Object 3 (has been added after button click)
What am I doing wrong? Can you please explain me the reason?
EDIT: I get this warning, but no error.
VirtualizedList: missing keys for items, make sure to specify a key or
id property on each item or provide a custom keyExtractor.,
import React, { Component } from "react";
import { Text, View, StyleSheet, Button, FlatList } from "react-native";
class App extends Component {
state = {
counter: 0,
initialElements: [
{ id: "0", text: "Object 1" },
{ id: "1", text: "Object 2" },
],
};
render() {
const currentCounter = this.state.counter;
const exampleState = this.state.initialElements;
const addElement = () => {
let newArray = [...exampleState, { id: "2", text: "Object 3" }];
this.setState({
initialElements: [newArray],
});
};
return (
<View style={styles.container}>
<View style={styles.counter}>
<Text style={styles.textStyle}>{currentCounter}</Text>
</View>
<View style={styles.deleteButton}>
<Button
title="Hello"
onPress={() =>
this.setState({
counter: currentCounter + 1,
})
}
></Button>
<View style={styles.space}></View>
<Button title="Delete" onPress={addElement}></Button>{" "}
{/* as soon as I click here, the content of the list is being deleted */}
</View>
<FlatList
style={styles.listStyle}
key={(item) => item.id}
data={exampleState}
renderItem={(item) => <Text>{item.item.text}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
justifyContent: "center",
flex: 1,
flexDirection: "column",
alignItems: "center",
},
counter: {
flexDirection: "row",
justifyContent: "center",
},
deleteButton: {
flexDirection: "row",
margin: 5,
marginTop: 100,
},
space: {
width: 5,
height: 5,
},
textStyle: {
margin: 80,
fontSize: 100,
},
listStyle: {
flexDirection: "column",
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
});
export default App;
I fixed it by changing the addElement to function to:
const addElement = () => {
var newArray = [...exampleState, {id : 2, text : "Object 3"}];
this.setState( {
initialElements: newArray
});
}
So, basically I changed
initialElements: [newArray]
to
initialElements: newArray
because newArray is already an Array, so no need to wrap it again.
I want year to be displayed on selection from dropdown list.
In this, selected item is being shown as alert I want to set text to the search box.
Here is the code:
import React, { useState, useEffect } from "react";
import {
StyleSheet,
SafeAreaView,
Text,
View,
TextInput,
Image,
Button,
FlatList,
TouchableOpacity,
} from "react-native";
import SearchableDropdown from "react-native-searchable-dropdown";
const years = [
{ id: 1, name: "2021" },
{ id: 2, name: "2020" },
{ id: 3, name: "2019" },
{ id: 4, name: "2018" },
{ id: 5, name: "2017" },
{ id: 6, name: "2016" },
{ id: 7, name: "2015" },
];
export default function Year() {
console.log("App Executed");
return (
<SafeAreaView>
<Text style={styles.headingText}>Select Year</Text>
<SearchableDropdown
onTextChange={(text) => console.log(text)}
// On text change listner on the searchable input
onItemSelect={(year) => alert(JSON.stringify(year))}
// onItemSelect called after the selection from the dropdown
containerStyle={{ padding: 5 }}
// suggestion container style
textInputStyle={{
// inserted text style
padding: 12,
borderWidth: 1,
borderColor: "#ccc",
backgroundColor: "#FAF7F6",
}}
itemStyle={{
// single dropdown item style
padding: 10,
marginTop: 2,
backgroundColor: "#FAF9F8",
borderColor: "#bbb",
borderWidth: 1,
}}
itemTextStyle={{
// text style of a single dropdown item
color: "#222",
}}
itemsContainerStyle={{
// items container style you can pass maxHeight
// to restrict the items dropdown hieght
maxHeight: "50%",
}}
items={years}
// mapping of item array
defaultIndex={"eg:2021"}
// default selected item index
placeholder="eg:2021"
// place holder for the search input
resetValue={false}
// reset textInput Value with true and false state
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
padding: 10,
},
titleText: {
padding: 8,
fontSize: 16,
textAlign: "center",
fontWeight: "bold",
},
headingText: {
padding: 10,
},
});
I was unable to use state
here is the solution
const years = [
{ id: 1, name: "2021" },
{ id: 2, name: "2020" },
{ id: 3, name: "2019" },
{ id: 4, name: "2018" },
{ id: 5, name: "2017" },
{ id: 6, name: "2016" },
{ id: 7, name: "2015" },
];
export default function Year() {
const [selectedItems, setSelectedItems] = useState();
console.log("App Executed");
return (
<SafeAreaView>
<SearchableDropdown
onTextChange={(text) => console.log(text)}
// On text change listner on the searchable input
selectedItems={selectedItems}
onItemSelect={(year) => setSelectedItems(year)}
// onItemSelect called after the selection from the dropdown
containerStyle={{ padding: 5 }}
// suggestion container style
textInputStyle={{
// inserted text style
padding: 12,
borderWidth: 1,
borderColor: "#ccc",
backgroundColor: "#FAF7F6",
}}
itemStyle={{
// single dropdown item style
padding: 10,
marginTop: 2,
backgroundColor: "#FAF9F8",
borderColor: "#bbb",
borderWidth: 1,
}}
itemTextStyle={{
// text style of a single dropdown item
color: "#222",
}}
itemsContainerStyle={{
// items container style you can pass maxHeight
// to restrict the items dropdown hieght
maxHeight: "50%",
}}
items={years}
// mapping of item array
defaultIndex={"eg:2021"}
// default selected item index
placeholder="eg:2021"
// place holder for the search input
resetValue={false}
// reset textInput Value with true and false state
/>
</SafeAreaView>
);
}
I SLOVED THAT BY THIS TRICK WAY:
const getTypeNameById_func = async id => {
const dataa = await accountsType.find(item => {
if (item.ID == id)
return item.NAME;
});
setTextSearchable(dataa.NAME);
};
AND IN SEARCHABLE DROPDOWN :
<SearchableDropdown
items={filterData}
placeholder={String(**textSearchable**)}
resetValue={false}
underlineColorAndroid="transparent"
onTextChange={text => console.log(text)}
onItemSelect={item => {
getTypeNameById_func(item.id);
setAccountType(item.id);
}}
defaultIndex={1}
/>
u can use useState variable and pass that variable in placeholder like:-
placeholder={variableName}
How can I change the font size and padding of the title cell in details list. I am using onRenderDetailsHeader prop to customize header render.
private renderDetailsHeader = (detailsHeaderProps: IDetailsHeaderProps) => {
return (
<DetailsHeader
{...detailsHeaderProps}
onRenderColumnHeaderTooltip={this.renderCustomHeaderTooltip}
/>
);
}
private renderCustomHeaderTooltip = (tooltipHostProps: ITooltipHostProps) => {
return (
<span
style={{
display: "flex",
fontFamily: "Tahoma",
fontSize: "10px",
justifyContent: "left",
paddingLeft: '0 px'
}}
>
{tooltipHostProps.children}
</span>
);
}
Codepen
In IDetailsHeaderProps['columns'] or simply IColumn[] => IColumn has 'headerClassName' key where you can specify the necessary styles to each of the column.
You can use the IDetailsColumnStyles interface to style the header cells.
Example:
...
const headerStyle: Partial<IDetailsColumnStyles> = {
cellTitle: {
color: theme.palette.orange,
}
}
const columns: IColumn[] = [
{ styles: headerStyle, key: 'name', name: 'Name', fieldName: 'name', minWidth: 100,},
...
Style the Row:
...
const renderRow: IDetailsListProps['onRenderRow'] = props => {
const rowStyles: Partial<IDetailsRowStyles> = {
root: {
borderBottomColor: theme.semanticColors.buttonBorder,
fontSize: theme.fonts.medium.fontSize,
},
cell: { paddingLeft: 0, },
}
if (!props) return null
return <DetailsRow {...props} styles={rowStyles} />
}
return (
<DetailsList
compact
items={items}
columns={columns}
selectionMode={SelectionMode.none}
layoutMode={DetailsListLayoutMode.justified}
constrainMode={ConstrainMode.horizontalConstrained}
onRenderRow={renderRow}
onRenderDetailsHeader={renderHeader}
onRenderItemColumn={renderItemColumn}
setKey="set"
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
checkButtonAriaLabel="Row Checkbox"
/>
)
...
I am using this package https://www.npmjs.com/package/react-native-picker-select
I've tried multiple methods to change the color of the RNPickerSelect placeholder text. But none of them have worked.
Tried the following ways:
style = {
{
inputIOS: {color: Constants.colour.black},
inputAndroid: {color: Constants.colour.black},
placeholderColor: Constants.colour.grey_90,
}
}
placeholder = {
label: placeholderText,
value: null,
color: Constants.colour.grey_90
};
UPDATE:
For Android you should set placeholder color in the style proportie like this, hope i can help someone :) :
style={{
placeholder: {color: Constants.colour.grey_50},
inputIOS: { color: Constants.colour.black },
inputAndroid: { color: Constants.colour.black },
}}
I will suggest you to always look in the issue board in the github repository of a package at first if there is no example in the package homepage. You might have found a solution there.
In this issue you will get your answer https://github.com/lawnstarter/react-native-picker-select/issues/100 .
Here is the example code:
<RNPickerSelect
placeholder={{
label: 'Select a color...',
value: null,
}}
placeholderTextColor="red"
items={this.state.items}
onValueChange={(value) => {
this.setState({
favColor: value,
});
}}
onUpArrow={() => {
this.inputRefs.name.focus();
}}
onDownArrow={() => {
this.inputRefs.picker2.togglePicker();
}}
style={{ ...pickerSelectStyles }}
value={this.state.favColor}
ref={(el) => {
this.inputRefs.picker = el;
}}
/>
The accepted answer doesn't work with the latest version (8.0.1, October 2020).
One needs to set
placeholder: {
color: 'red',
}
in the style parameter, see
https://github.com/lawnstarter/react-native-picker-select/issues/100#issuecomment-622469759
in my case, i used:
const pickerStyle = {
inputIOS: {
color: 'white',
paddingHorizontal: 10,
backgroundColor: 'red',
borderRadius: 5,
},
placeholder: {
color: 'white',
},
inputAndroid: {
color: 'white',
paddingHorizontal: 10,
backgroundColor: 'red',
borderRadius: 5,
},
};
return (<RNPickerSelect style={pickerStyle} ... />)
This worked for me
style={{
placeholder: {
color: 'red',
},
}}