React Native - Calling Flatlist item outside the Flatlist itself - javascript

I'm trying to have a Send Order Button below my FLATLIST where this Send Order Button will send the states to the other screen/view together with the item in my Flatlist.
"But the problem is I don't know how to call the Flatlist's item outside the Flatlist itself."
Here's my code
export default class Settlement extends Component {
constructor(props){
super(props)
this.state = {
......
}
fetchData = async () => {
....
this.setState({ data: json })
}
render() {
return (
<View>
<Text>Table No: { this.state.tbl }</Text>
<Text>{ this.state.DineIn }{ this.state.TakeOut }</Text>
<FlatList
data = {this.state.data}
renderItem = {({ item }) =>
<View>
<View>
<Text>{ item.item.order_id }</Text>
<Text>Name: { item.menu_name }</Text> //Flatlist_Items
<Text>Price: ₱{ item.menu_price }</Text>
<Text>Discount: { item.order_discount }</Text>
<Text>Amount: ₱{ item.order_amount }</Text>
.....
<Text>{ item.spcl_req }</Text>
<Text>{ item.order_quantity }</Text>
.....
</View>
</View>
}/>
</View>
<Text>Number of Orders: { this.state.numOrder }</Text>
<Text>Total Amount: ₱{ this.state.TotalSum }</Text>
<TouchableOpacity
onPress = { () => this.props.navigation.navigate('FinalSettlement', {
orderID : item.order_id,
Name : item.menu_name,
Price : item.menu_price, //Trying to pass
Ord_QTY : item.order_quantity, // the items to other view
spcl_req : item.spcl_req,
Discount : item.order_discount,
Amount : item.order_amount,
tbl : this.state.tbl,
pax : this.state.pax,
DineIn : this.state.DineIn,
TakeOut : this.state.TakeOut,
numOrder : this.state.numOrder,
TotalSum : this.state.TotalSum,
userName : this.state.userName
})}>
<Text>SEND ORDER</Text>
</TouchableOpacity>
</View>
</View>
)
}
}

Please look at the RN doc, list item should be separate component as mentioned in doc
_renderItem = ({item}) => (
<MyListItem
id={item.id}
onPressItem={this._onPressItem}
selected={!!this.state.selected.get(item.id)}
title={item.title}
/>
);
render() {
return (
<FlatList
data={this.props.data}
extraData={this.state}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
And instead of passing a lot of param in navigation function you can use global statement, for example Redux.
In your case you can get params in your screen 'FinalSettlement' by getParam function from ReactNavigation

Related

Function inside Flatlist RenderItem is not fully working

Problem is I cannot see {item.key} inside my function. When I type {item.key} itself inside flatlist render it is working. But inside function only {item.value} is showing. Can anyone explain to me why this happening ?
Sample Data
const orderResultJson = [
{
key: 'Скачайте приложение по ссылке',
value: 'https://google.com'
},
{
key: 'Логин',
value: '879854'
},
{
key: 'Пароль',
value: '849846'
},
];
My Function
function DetailsSection(item){
return(
<View>
<Text>{item.value}</Text>
<Text>{item.key}+test</Text>
</View>
)
}
Render
render() {
return (
<View style={styles.container}>
<FlatList
data={orderResultJson}
renderItem={({item}) => <DetailsSection {...item} />}
keyExtractor={item => item.key}
/>
</View>
);
}
Problem here is, when you are deconstructing item as individual props, the prop key will be considered as in built react prop key instead of considering it as an external prop.
So instead of deconstructing, pass item as is and access it from your function as it is.
My Function
function DetailsSection({ item }){
return(
<View>
<Text>{item.value}</Text>
<Text>{item.key}+test</Text>
</View>
)
}
Render
render() {
return (
<View style={styles.container}>
<FlatList
data={orderResultJson}
renderItem={({item}) => <DetailsSection item={item} />}
keyExtractor={item => item.key}
/>
</View>
);
}
function DetailsSection(props){
return(
<View>
<Text>{props.item.key} + test</Text>
<Text>{props.item.value}</Text>
</View>
)
}
Or
pass like this
<DetailsSection item={item} />
and access like this
function DetailsSection({ item }){
return(
<View>
<Text>{item.value}</Text>
<Text>{item.key}+test</Text>
</View>
)
}
because you are passing extracted value so directly you can access

How do I navigate between List and Item?

I am trying to open an item from my list but my item code is in another js. When I try to use onPress method there is no action. Also I am using Swipeout.
Here is my JobList.js where I am rendering the list of my items.
class JobList extends Component {
onJobDetails = (job) => {
this.props.navigate('JobDetails', job);
}
render() {
const { navigation } = this.props;
var renderJobs = () => {
return this.props.jobs.map((job) => {
return (
<JobItem
key={job._id}
title={job.title}
shortDescription={job.shortDescription}
logo={job.avatar}
company={job.company}
id={job._id}
dispatch={this.props.dispatch}
onPress={() => this.onJobDetails(job)}
/>
)
})
}
return (
<View style={styles.container}>
<ScrollView>
{renderJobs()}
</ScrollView>
</View>
);
}
};
And here is my JobItem.js
class JobItem extends Component {
render() {
return (
<Swipeout {...swipeSettings}>
<View style={styles.jobContainer}>
<View>
<Text style={styles.postTitle}>{this.props.title}</Text>
<Text style={styles.postShortDescription}>{this.props.shortDescription}</Text>
</View>
<View>
<Image
style={styles.postLogo}
source={{uri: '' + this.props.logo + ''}}/>
</View>
</View>
</Swipeout>
)
}
};
Any idea how shall I fix this?
You need to pass onPress prop to the child component in order for it to work.
<Swipeout {...swipeSettings}>
<TouchableWithoutFeedback onPress={this.props.onPress}>
//... other children here
</TouchableWithoutFeedback>
</Swipeout>

How to pass props from FlatList item to Modal?

I have implemented a View component containing a FlatList, which renders TouchableHighlights. Also I have implemented a Modal component, which I'd like to import at various places including the component that renders the FlatList.
I have already managed to open the modal from outside (via handing over a prop for visibility, accessing it via nextProps and setting modals state value "modalVisible" to this) and closing it from inside (simply via changing it's state value "modalVisible").
BUT: I also want to pass data to the modal from each FlatLists item. An item rendered as a TouchableHighlight should open the modal onPress and the modal should contain data from the item (in the code below this would be the items id). How can I achieve passing data to the modal? I somehow can't get it to work using nextProps. This seems more to be an issue related to setting state from within a FlatLists item rather than the Modal.
Modal:
export default class ModalView extends React.Component {
constructor() {
super();
this.state = {
modalVisible: false,
id: null,
};
}
componentWillReceiveProps(nextProps) {
this.setState({
modalVisible: nextProps.modalVisible,
id: nextProps.id,
})
}
render() {
return (
<Modal
animationType="slide"
transparent={ true }
visible={ this.state.modalVisible }
onRequestClose={() => { this.props.setModalVisible(false) }}
>
<View>
<View>
<Text>{ this.state.id }</Text>
<TouchableHighlight
onPress={() => { this.props.setModalVisible(false) }}
>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
)
}
}
FlatList rendering TouchableHighlights:
export default class RecentList extends React.Component {
constructor() {
super();
this.state = {
modalVisible: false,
id: null,
}
}
_onPressItem(id) {
this.setState({
modalVisible: true,
id: id,
});
};
_renderItem = ({item}) => {
return (
<TouchableHighlight
id={item.id}
onPress={this._onPressItem}
>
<View>
<Text>{id}</Text>
</View>
</TouchableHighlight>
)
};
render() {
let data = realm.objects('Example').filtered('completed = true')
.sorted('startedAt', true).slice(0, 10)
return (
<View>
<ModalView
modalVisible={ this.state.modalVisible }
setModalVisible={ (vis) => { this.setModalVisible(vis) }}
id={ this.state.id }
/>
<FlatList
data={data}
renderItem={this._renderItem}
keyExtractor={(item, index) => index}
/>
</View>
)
}
}
A small mistake you have missed ...
_renderItem = ({item}) => {
return (
<TouchableHighlight
id={item.id}
onPress={() => this._onPressItem(item.id)} // Your not sending the item.id
>
<View>
<Text>{id}</Text>
</View>
</TouchableHighlight>
)
};

How refresh the ListView Component in react native?

I'm trying to create a todo list, then I'm trying to use this checkbox package
react-native-check-box
I don't know if this issue come from that package
when I click the checkbox and click the delete button this is what happen
And here is my code for displaying the list
interface TodoProps{
todo: TodoModel;
ter:string;
}
interface TodoState{
dataSource: any;
myTodo: Array<ITodo>;
}
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => true});
export default class Todo extends React.Component <TodoProps,TodoState>{
constructor(props:TodoProps) {
super(props);
this.state = {
dataSource: ds.cloneWithRows([]), // or put your initial data here
myTodo: []
};
}
componentWillReceiveProps = (nextProps) => {
console.log(this.state.myTodo);
let data = {
title: nextProps.ter,
isChecked: false
};
let todoList = this.state.myTodo;
if (nextProps.ter) {
todoList.push(data);
}
this.setState({
myTodo: todoList
});
}
onDelete(){
let todos = this.state.myTodo.filter((todo:ITodo) => {
return !todo.isChecked;
});
this.setState({
myTodo: todos
});
}
render() {
let dataSource = this.state.dataSource.cloneWithRows(this.state.myTodo);
return (
<View style={styles.container}>
<View style={styles.box2}>
<ListView enableEmptySections={true} dataSource={dataSource} renderRow={(rowData, sectionID, rowID) => <TodoList data={rowData} onClick={this.onClick.bind(this)} id={rowID} /> } />
</View>
<View style={styles.box3}>
<TouchableOpacity style={styles.bbox1} onPress={()=> alert('weee')}>
<Text style={styles.tabText}>All</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.bbox2} onPress={()=> alert('weee')}>
<Text style={styles.tabText}>Complete</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.bbox3} onPress={()=> alert('weee')}>
<Text style={styles.tabText}>InComplete</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.bbox4} onPress={()=> this.onDestroy()}>
<Text style={styles.tabText}>Delete</Text>
</TouchableOpacity>
</View>
</View>
)
}
}
But if I console log the data. I find all isChecke: to false. Only the view of checkbox is not working. Do I need to use componentwillamount() for this?
Use the below sample code
_onRefresh() {
this.setState({refreshing: true});
// your callback function or call this.componentDidMount()
}
render() {
return (
<ListView
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
/>
}
...
>
...
</ListView>
);
}

React-Native Navigation without render command

Is there anyway to redirect user to a different component (also passing arguments with it) without calling render function?
almost in all tutorials i found, they use sameway :
render() {
return (
<NavigatorIOS
style={styles.container}
initialRoute=\{\{
title: 'first',
component: First
}} />
);
}
Now see my code :
in renderRow , for touchablehighlights , i need to be able to redirect user to a page with an argument, (in this case i need to send user to component CourseDetail with argument of course_id, so i can show user course's details)
class Courses extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
}
fetchData() {
// fetching data here
}
componentDidMount() {
this.fetchData();
}
render(){
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<View style={{
flex: 1
}}>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
</View>
);
}
renderRow(data) {
var header = (
<View>
<View style={styles.rowContainer}>
<View style={styles.textContainer}>
<Text style={styles.title}>{data.nid}</Text>
<Text style={styles.description} numberOfLines={0}>{data.title}</Text>
</View>
</View>
<View style={styles.separator}></View>
</View>
);
///////////
var cid = [];
var content = [];
for(let x=0; x < Object.keys(data.course).length; x++){
cid[x] = data.course[x].course_id;
content.push(
<TouchableHighlight
underlayColor='#e3e0d7'
key={x}
onPress={()=>{console.log(cid[x]);}} //// i need to navigate user to a page with passing arguments (course_id in this case)
style={styles.child}
>
<Text style={styles.child}>
{data.course[x].title}
</Text>
</TouchableHighlight>
);
}
console.log(cid);
var clist = (
<View style={styles.rowContainer}>
{content}
</View>
);
////////////
return (
<Accordion
header={header}
content={clist}
easing="easeOutCubic"
/>
);
}
renderLoadingView() {
return (
<View style={styles.loading}>
<Text style={styles.loading}>
Loading Courses, please wait...
</Text>
</View>
);
}
}
module.exports = Courses;
Thanks in Advance!
By help of this Question here :
React-Native: Cannot access state values or any methods declared from renderRow
I was able to solve the issue by changing :
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
To :
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
style={styles.listView}
/>
Hope it will help others who may have the same problem.

Categories

Resources