Adding fresh elements to the state array in React Native

I am experiencing an issue with the code provided below:

import React, { Component } from "react";
import { SafeAreaView } from 'react-navigation'
import {Keyboard, Text, View, TextInput, TouchableWithoutFeedback, Alert, KeyboardAvoidingView, StyleSheet} from 'react-native';
import { Button } from 'react-native-elements';
import EditableTable from 'react-native-editable-table';

export default class CreateNoteScreen extends Component {

constructor(props){
    super(props)
    this.state = {
        NotesHeader : [
          {value: 'Expend', input: 'c1', width: 30, sortable: false, defaultSort: 'ASC',editable: true},
          {value: 'Value', input: 'c2', width: 20, sortable: false, editable: true}
        ],
        NotesValue: [
          [10, 'test'],
          [20, {value: 'Edit Me', editable: true}],
          [30, {value: 'Extra Editable Rows',editable:true}],
          [20, {value: 'Edit Me', editable: true}],
          [20, {value: 'Edit Me', editable: true}],
          [20, {value: 'Edit Me', editable: true}],
          [20, {value: 'Edit Me', editable: true}],
          [20, {value: 'Edit Me', editable: true}],
          [10, 'test'],
          ['', ''],
          ['', '']
        ]
    }
}

_addNewColumn = () =>{

  let newNotesvalues = this.state.NotesValue.map(function(item) {
    item = [...item,[ 
      '',
      {
      value: ' ',
      editable: true
    }]
  ];
    return item;
  });

this.setState(prevState => ({
  NotesHeader: [...prevState.NotesHeader, {
    value: 'Value',
    input: 'c3',
    width: 20,
    sortable: false,
    editable: true
  }],
  NotesValue: newNotesvalues
}))

render(){
    return (
      <SafeAreaView style={styles.container}>
      <Button title="Add column" onPress={() => this._addNewColumn()} />
        <EditableTable
          columns ={ this.state.NotesHeader }
          values= {this.state.NotesValue}
          emptyRows={2}
          onCellChange={(value, column, row, unique_id) => {
            console.log(`Cell Change on Column: ${column} Row: ${row}
                        and unique_id: ${unique_id}`);
          }}
          onColumnChange={(value, oldVal, newVal) => {
            console.log(`Column Change. Old Value: ${oldVal} New Value: ${newVal}`)
          }}
          customStyles={{

          }}
          style={styles.table}
        />
      </SafeAreaView>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#F5FCFF'
  },
  table: {
    flex: 1,
    marginBottom: 30
  }
});

NoteHeader represents the table header while NoteValue contains the table rows.

In the _addNewColumn function, I am trying to add a new column with blank values in the rows.

You can find the code to this snippet here:

While testing, I encountered an error and despite trying different approaches, I have not been successful. The error message states:

Cannot read property 'hasOwnProperty' of undefined TypeError: Cannot read property 'hasOwnProperty' of undefined at eval (module://react-native-editable-table.js:3:4930)

I would appreciate any help or guidance on resolving this issue effectively.

Answer №1

Array#push provides the new length of an array, and then attempts to add that to NotesHeader using spreading. Modify it to:

this.setState(prevState => ({
  NotesHeader: [...prevState.NotesHeader, {
    value: 'Value',
    input: 'c3',
    width: 20,
    sortable: false,
    editable: true
  }],
  NotesValue: newNotesvalues
}))

Also implement array spreading in _addNewColumn

_addNewColumn = () => {

  let newNotesvalues = this.state.NotesValue.map(function(item) {
    item = [...item, {
      value: ' ',
      editable: true
    }]
    return item;
  });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a simpler and more refined approach for handling Observables within RxJS pipelines?

Picture this: I have an observable that gives me chocolate cookies, but I only want to eat the ones without white chocolate. Since I am blind, I need to send them to a service to determine if they are white or not. However, I don't receive the answer ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

Scrolling with Buttons in both Right and Left directions

I am working with three divs: left, middle, and right. The middle div will contain content, while the left and right divs are designated for buttons that will scroll the middle div. Specifically, I plan to display lists of pictures in the middle div. If a ...

The toggler in Bootstrap 5's Navbar menu is experiencing difficulties opening on mobile browsers

Just arrived here for the first time. Encountering an issue with my Bootstrap 5.1 Navbar menu. Background info: My website is hosted locally via Xampp with php pages for forms and cookies. Everything functions perfectly on desktop. Checked responsiveness o ...

Unusual hue in the backdrop of a daisyui modal

https://i.stack.imgur.com/fLQdY.png I have tried various methods, but I am unable to get rid of the strange color in the background of the Modal. Just for reference, I am using Tailwind CSS with Daisy UI on Next.JS. <> <button className='btn ...

Emphasizing sections using a specific class for paragraph highlighting

Is it possible to dynamically change the style of paragraphs based on certain classes? Let's say we have a text with a list of p elements and we want to modify the styles of paragraphs that come after specific classes, such as 'alert' or &ap ...

Is it necessary for the keys in separate loops to be unique among siblings?

Does the use of key in loops create separate branches, or do they still need to be unique for the same parent? Take a look at this example: // This is obviously an error: <div> <div key="gimme-a-break" /> <div key="gim ...

Render function in Next.js did not yield anything

Recently, I came across the next.js technology and encountered an error. Can anyone help me solve this issue? What could be causing it?View image here import React from 'react' import Button from "../components/button" function HomePa ...

Transferring the link value to an AJAX function when the onclick event is triggered

I have a link containing some data. For example: <li><a href="" onclick="getcategory(this);"><?php echo $result22['category']; ?></a></li> I need this link to pass the value of $result22['category']; to ...

Invoke another component to display within a React.js application

Click here to view the code snippet. I am facing an issue with my React components. I have component A that handles fetching and rendering a list, and I also have component B that accepts user input. How can I trigger component A from component B? It seem ...

An easy guide to comparing date and time using Moment.js

Hey there, I'm looking for some help in validating two instances of date time moments. I am using this helpful Package which allows us to select hour, minute, and second. I want to validate whether the selected date time is before or after, as shown i ...

Retrieving InnerHTML of a Rendered DOM Element in AngularJS

Can I retrieve the innerHTML code of a rendered element that contains an ng-repeat loop? Here is an example: <div id="container"> <div ng-repeat="e in ctrl.elements>{{e.name}}</div> </div> ...

"Enhabling tablesorter pagination to ensure that buttons always stay in sync with

I am experiencing an issue with the pagination buttons staying at the bottom of my page, even when there are only 2 entries left on the last page. Check out my table here: Is there a way to make the pagination buttons dynamically move to the top based on ...

"Learn the steps to enable a click-to-select feature for an item, allowing you to drop it in a different location

I've been spending quite some time trying to come up with a solution for my dilemma. The issue arises because I'm not looking to use drag and drop functionality. https://i.stack.imgur.com/Nh1Db.png My goal is to have 3 divs named 1,2,3 as desig ...

I am eager to retrieve the outcome once all the queries have been completed within the loop (using express.js, react.js, and MySQL)

Currently, I am engaged in a personal project that involves using React and Express. The task at hand is to retrieve data spanning 7 days for a specific item from my database and present it in a search list. To achieve this, I attempted the following: U ...

The ng-switch function is not generating the desired code output

In my Ionic app, I have the following code snippet that I am currently viewing with ionic serve. However, when the initial ng-switch statement triggers... <span ng-switch="post.enclosure"> <span ng-switch-when="[]"> <p>def&l ...

The Vue3 counterpart of vNode.computedInstance

I'm currently in the process of upgrading my app from Vue2 to Vue3, but I've hit a roadblock when it comes to dealing with forms. For my form elements, such as FormInput, FormTextArea, and FormCheckbox, I have been using Single File Components ( ...

Error: Unable to execute fields.map function while generating a dynamic sitemap using next-sitemap module

I'm in the process of creating a dynamic sitemap for my website and here's the code I'm using: import { GetServerSideProps } from 'next'; import { getServerSideSitemap, ISitemapField } from 'next-sitemap'; import { makeSl ...

After consolidating buffer geometries, adjusting the transparency/opacity of the shapes is not an option for me

I've been working on a model with multiple boxes and trying to optimize draw calls by using buffer geometry merger. However, I'm facing an issue where I can't change the opacity of geometries after merging. Here are the things I've tri ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...