React-Native Updating List View DataSource - javascript

I have an iOS app I am making with react-native. The Game class contains a ListView component. I set the state in the constructor and include a dataSource. I have a hardcoded array of data for right now that I store in a different state property (this.state.ds). Then in the componentDidMount I use the cloneWithRows method to clone my this.state.ds as my dataSource for the view. That is pretty standard as far as ListViews go and is working well. Here is the code:
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
var React = require("react-native");
var { StyleSheet, Text, View, ListView, TouchableHighlight } = React;
class Games extends React.Component {
constructor(props) {
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 != r2
});
this.state = {
ds: [
{ AwayTeam: "TeamA", HomeTeam: "TeamB", Selection: "AwayTeam" },
{ AwayTeam: "TeamC", HomeTeam: "TeamD", Selection: "HomeTeam" }
],
dataSource: ds
};
}
componentDidMount() {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(this.state.ds)
});
}
pressRow(rowData) {
var newDs = [];
newDs = this.state.ds;
newDs[0].Selection = newDs[0] == "AwayTeam" ? "HomeTeam" : "AwayTeam";
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newDs)
});
}
renderRow(rowData) {
return (
<TouchableHighlight
onPress={() => this.pressRow(rowData)}
underlayColor="#ddd"
>
<View style={styles.row}>
<Text style={{ fontSize: 18 }}>
{rowData.AwayTeam} # {rowData.HomeTeam}{" "}
</Text>
<View style={{ flex: 1 }}>
<Text style={styles.selectionText}>
{rowData[rowData.Selection]}
</Text>
</View>
</View>
</TouchableHighlight>
);
}
render() {
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow.bind(this)}
/>
);
}
}
var styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: "row",
padding: 18,
borderBottomWidth: 1,
borderColor: "#d7d7d7"
},
selectionText: {
fontSize: 15,
paddingTop: 3,
color: "#b5b5b5",
textAlign: "right"
}
});
module.exports = Games
The issue I am having comes in the pressRow method. When the user presses the row, I would like the selection to change and for it to render the change on the device. Through some debugging, I have noticed that even though I am changing the Selection property of the object in the newDs array, the same property changes on the object in this.state.ds and similarly changes the object in this.state.dataSource._dataBlob.s1. Through further debugging, I have found that since those other arrays have changed, the ListView's DataSource object doesn't recognize the change because when I set the state and rowHasChanged is called, the array it is cloning matches the array this.state.dataSource._dataBlob.s1 and so it doesn't look like a change and doesn't rerender.
Any ideas?

Try this:
pressRow(rowData){
var newDs = [];
newDs = this.state.ds.slice();
newDs[0].Selection = newDs[0] == "AwayTeam" ? "HomeTeam" : "AwayTeam";
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newDs)
})
}
This should make a copy of the array, which can then be modified independently of the original array in this.state.ds.

In case anyone comes across this issue like I did, here's the complete solution.
Basically, there seems to be a bug with the ListView component and you need to rebuild each item that changes in the datasource for the ListView to redraw it.
First, create the datasource and a copy of the array and save them to state. In my case, foods is the array.
constructor(props){
super(props);
var ds = new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
});
this.state = {
dataSource: ds.cloneWithRows(foods),
db: foods,
};
}
When you want to change something in the datasource, make a copy of the array you saved to the state, rebuild the item with the change and then save the new array with the change back to the state (both db and datasource).
onCollapse(rowID: number) {
console.log("rowID", rowID);
var newArray = this.state.db.slice();
newArray[rowID] = {
key: newArray[rowID].key,
details: newArray[rowID].details,
isCollapsed: newArray[rowID].isCollapsed == false ? true : false,
};
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newArray),
db: newArray,
});
}

react is smart enough to detect changes in dataSource and if the list should be re-rendered. If you want to update listView, create new objects instead of updating the properties of existing objects.
The code would look something like this:
let newArray = this._rows.slice();
newArray[rowID] = {
...this._rows[rowID],
Selection: !this._rows[rowID].Selection,
};
this._rows = newArray;
let newDataSource = this.ds.cloneWithRows(newArray);
this.setState({
dataSource: newDataSource
});
You can read more about similar issue on Github

Related

How to create an array of objects in React Native from seperate components?

I'm new to React Native, so I understand I have alot to learn.
I'm creating a custom class component here:
import React, { Component, useState } from 'react';
import {View,Text,StyleSheet,TextInput, Button} from 'react-native';
class Square extends React.Component{
constructor(pos,text,won,save){
this.state = {
pos : 0,
text : 'EDIT',
won : false,
save : false,
};
}
setPos = (pos) =>{
this.setState(pos)
}
getPos = () => {
return (this.pos);
}
setText=(text)=>{
this.setState(text)
}
getText=()=>{
return (this.text);
}
setWon=(won)=>{
this.setState(won)
}
getWon=()=>{
return (this.won);
}
setSave=(save)=>{
this.setState(save)
}
getSave=()=>{
return (this.save);
}
};
export default Square;
Then I want to create an array of those objects in a different component and display a piece of information from each object.
import {View, Text, StyleSheet, Button, Alert} from 'react-native';
import Square from '../components/Square';
const NewGameScreen = () => {
let arrSquare = [];
for (let i = 0; i < 25; i++){
arrSquare.push({
THIS IS WHERE I'M HAVING TROUBLE
});
}
console.log(arrSquare[0].getPos)
return(
<View style = {styles.screen}>
<View style = {styles.row}>
<Text>{arrSquare[0].getPos}</Text>
</View>
</View>
)
};
However from the above code I'm sure it's clear I'm missing something. I would have expected to use something like Square[i].setPos(i); but that throws errors. The console log also gives 'undefined' so that makes me think I haven't declared something or haven't declared it properly. Thanks in advance.
well the way I would go about this is to have a simple array of json object something like this:
let squareArr = [{
id: 0,
pos : 0,
text : 'EDIT',
won : false,
save : false,
},
{
id: 1,
pos : 0,
text : 'EDIT',
won : false,
save : false,
},
{
id: 2,
pos : 0,
text : 'EDIT',
won : false,
save : false,
}
]
then you can do the the read and the edit.
to display a position:
in your render method you can do this:
<View style = {styles.screen}>
<View style = {styles.row}>
squareArr.map((square) => <Text>{square.pos}</Text>)
</View>
</View>
to edit a position:
if you want to change a value in your JSON then just use the object index as a way to indicate which object you wanna change. For example want to change the pos of the second object then I would do this:
squareArr[1].pos = 3
I am not quite sure what is the whole project is to give you to give you the best solution but i hope this helps..
feel free to ask if you have any questions

Update child component props from Parent component react native

I want to update child component props from Parent component my senarios is I have one component which I am passing one array list which is come from API response so below is my code
<DateRangePicker
theme={{
calendarBackground: colors.white,
selectedDayBackgroundColor: colors.kellyGreen,
selectedDayTextColor: colors.white,
todayTextColor: colors.kellyGreen,
dayTextColor: colors.intrestedButton,
dotColor: colors.kellyGreen,
selectedDotColor: colors.kellyGreen,
arrowColor: colors.kellyGreen,
monthTextColor: colors.black,
textDayFontFamily: globals.SFProTextRegular,
textMonthFontFamily: globals.SFProTextMedium,
textDayHeaderFontFamily: globals.SFProTextMedium,
textMonthFontWeight: "bold",
textDayFontSize: globals.font_11,
textMonthFontSize: globals.font_16,
textDayHeaderFontSize: globals.font_13
}}
minDate={null}
isFrom={'golfActivity'}
monthFormat={globals.selectedLocal.DATE_MMMMyyyy}
initialRange={[this.state.fromDate, this.state.toDate]}
onSuccess={(s, e) => this.setState({ fromDate: e, toDate: s })}
theme={{ markColor: colors.kellyGreen, markTextColor: colors.white
}}
underLineValue = {this.state.underLineValue}
onVisibleMonthsChange={months => { this.getChangeMonth(months) }}
/>
in above code underLineValue is my array list which is come from API side and when I change month at that time i onVisibleMonthsChange props is called and I get newly updated month and year so again I am calling API for that and fill new my updated array refer my getChangeMonth method as below
getChangeMonth = (months) => {
countCall = countCall + 1
if (countCall === 1) {
this.setState({isMonthChange: true})
visibleMonth = months[months.length - 1].month;
visibleYear = months[months.length - 1].year;
globals.visibleMonth= visibleMonth;
globals.visibleYear= visibleYear;
console.log("on visible month", visibleMonth);
console.log("on visible year", visibleYear);
this.callCounterAPI(visibleMonth, visibleYear);
countCall = - 1
}
}
callCounterAPI(month, year){
this.setState({ underLineValue: []})
API.getCalendarCount(this.onResponseCalendarCount, month, year,true)
}
onResponseCalendarCount = {
success: (response) => {
this.setState({underLineValue: response.data })
},
error: (err) => {
console.log("onResponseCalendarCount error-->>", err);
},
complete: () => {
}
}
export default class DateRangePicker extends Component<Props> {
state = { isFromDatePicked: false, isToDatePicked: false, markedDates: {} }
componentDidMount() {
console.log("DateRangePicker-->"+ JSON.stringify(this.props));
}
}
onResponseCalendarCount callback I fill updated arraylist underLineValue but in DateRangePicker when i print it's props I did't get updated arraylist so any one have idea how can i solve this issue? Your all suggestions are welcome
You can use getDerivedStateFromProps method in child component like this:
import isEqual from 'lodash/isEqual'
static getDerivedStateFromProps(props, state) {
if (!isEqual(props.underLineValue, state.underLineValue)) {
return {
underLineValue: props.underLineValue
}
}
return null;
}
This will update your child component. Let me know if it's working.

Label text not updating in MUIDataTable ReactJS

I want to add multi language option in mui Datatables. I can change the translations but when I want to change language, I tried to give another object with the other translations (this object if I do console log I can see the changes) but the label texts not change.
I used a contextProvider to change the language selected and then get the specific dictionary with the translations.
Is a class component, so I did a static contextType with the correct provider.
Is there any possibility to re-render the element with another options or something like that?
options = {
textLabels: this.context.translation.dataTables.textLabels
};
return(
<MUIDataTable
title={this.context.language.value}
data={data}
columns={columns}
options={options}
/>
);
The best approach to re-render Mui-Datatables its updating the key of the table
key={this.context.language.value}
<MUIDataTable
key={this.context.language.value}
title={this.context.language.value}
data={data}
columns={columns}
options={options}
/>
You can force React component rendering:
There are multiple ways to force a React component rendering but they are essentially the same. The first is using this.forceUpdate(), which skips shouldComponentUpdate:
someMethod() {
// Force rendering without state change...
this.forceUpdate();
}
Assuming your component has a state, you could also call the following:
someMethod() {
// Force rendering with a simulated state change
this.setState({ state: this.state });
}
use customRowRender Function in the options and manipulate table with respect to language
Override default row rendering with custom function.
customRowRender(data, dataIndex, rowIndex) => React Component
In MUIDataTable, We can override label name by providing label in MUIDataTableColumnDef options while making column.
Example :
const columns: MUIDataTableColumnDef[] = [
{
name: 'Id',
label: 'ID',
options: {
download: false,
customBodyRenderLite: (index: number) => {
const desc: Description = evenMoreAbout[index]
return <BasicInfo obj={desc} setIconClicked={setIconClicked} />
}
}
},
{
name: 'id',
label: 'ID',
options: {
display: 'excluded',
download: true,
customBodyRender: desc => desc.id
}
}]
Even though if we still want to over ride the label name on some condition of data using customHeadLabelRender ... we can as like below example
const columns: MUIDataTableColumnDef[] = [
{
name: 'Id',
label: '',
options: {
download: false,
customBodyRenderLite: (index: number) => {
const desc: Description = evenMoreAbout[index]
return <BasicInfo obj={desc} setIconClicked={setIconClicked} />
},
customHeadLabelRender: (dataIndex: number, rowIndex: number) => {
return 'ID';
}
}
}
]

Vis.js/React/JavaScript: Render Vis.timeline

I am in the middle of trying to solve a problem with vis.js timeline I hope to get some guidance from you folks. console.log is showing data but the browser shows a blank screen. Unfortunately I am all out of ideas on what else to try it to make it work.
I have the following code. I have tried different ways to make it work but so far no luck. Any help will be greatly appreciated.
// Config for the Timeline as JSON
const options = {
width: '100%',
height: '60px',
stack: false,
showMajorLabels: true,
showCurrentTime: true,
zoomMin: 1000000,
type: 'background',
format: {
minorLabels: {
minute: 'h:mma',
hour: 'ha'
}
}
}
class ScaleTime extends Component{
constructor({data=[]}) {
super({data})
this.state = {data, id:''}
//console.log('ScaleTime Data:', data)
}
render(){
const { data } = this.state
const newAction = data.action.map((actionItem, index) => ({
...actionItem,
id: index + 1
}));
const items = {
...data,
action: newAction
};
const timeLineData = new vis.DataSet([{items}])
console.log('timeLineData:', timeLineData)
var container = document.getElementById('timeline');
return(
<div className="timeline">
<Timeline
items={items.action}
options={options}
container={container}
/>;
</div>
)
}
}//component
Update:
After adding id now I need to change the 'timestamp' property to start. The error message I am now getting is: Property "start" missing in item 1.
you need to make sure that items has content before calling Timeline. You can do:
if (!items) return <SpinLoader />; return <Timeline items={items.action} options={options} container={container} />;

How to save data in an array inside state in react js

I have TextField and FlatButton inside the Dialog. I want to save complete task list in an array which I defined in a state.
this.state = {
open: false,
todos: [{ id: -1, text: "", completed: false }],
notetext: ""
};
I am able to get text of TextField from the state. I want to save task in an array on clicking of FlatButton. I have handleCreateNote function which is attached on tap on FlatButton.
I don't know what is the way to add task in an array. Can anyone help me what is the way in the react ?
const AppBarTest = () =>
<AppBar
title={strings.app_name}
iconClassNameRight="muidocs-icon-navigation-expand-more"
style={{ backgroundColor: colors.blue_color }}
/>;
class App extends Component {
constructor(props) {
injectTapEventPlugin();
super(props);
this.state = {
open: false,
todos: [{ id: -1, text: "", completed: false }],
notetext: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
handleCreateNote = () => {
console.log(this.state.notetext);
};
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<MuiThemeProvider>
<div>
<AppBarTest />
<FloatingActionButton
style={styles.fab}
backgroundColor={colors.blue_color}
onTouchTap={this.handleOpen}
>
<ContentAdd />
</FloatingActionButton>
<Dialog
open={this.state.open}
onRequestClose={this.handleClose}
title={strings.dialog_create_note_title}
>
<TextField
name="notetext"
hintText="Note"
style={{ width: "48%", float: "left", height: 48 }}
defaultValue={this.state.noteVal}
onChange={this.handleChange}
/>
<div
style={{
width: "4%",
height: "48",
backgroundColor: "red",
float: "left",
visibility: "hidden"
}}
/>
<FlatButton
label={strings.create_note}
style={{ width: "48%", height: 48, float: "left" }}
onTouchTap={this.handleCreateNote}
/>
</Dialog>
</div>
</MuiThemeProvider>
);
}
}
export default App;
First create a copy of existing state array, then use array.push to add a new data, then use setState to update the state array value.
Like this:
handleCreateNote = () => {
let todos = [...this.state.todos]; //creating the copy
//adding new data
todos.push({
id: /*unique id*/,
text: this.state.notetext,
completed: false
});
//updating the state value
this.setState({todos});
};
Check this answer for details about "..." --> What do these three dots in React do?
MDN: Spread Operator
Update:
Instead of spread operator you can also use slice(), that will also return a new array, the key point is we need to create a copy of state array (before doing any change) by using any method.
Check this snippet:
let a = [{key: 1}, {key: 2}];
let b = [...a];
console.log('b', b);
you can use concat to create a new array:
this.setState({
todos: [].Concat(this.state.todos, {id, text, complete})
})

Categories