React Native : Dynamically Created TextBox value is not getting updated

Asked
Active3 hr before
Viewed126 times

8 Answers

nativevaluereact
90%

I'm little new to React Native. I have a scenario where I need to create the TextInput dynamically and bind values it from an array. Once the array updates, the value of the TextInput is not updating. Below is my code. , Does electron physically move in an interband transition? , Can I avoid informal personal interactions at companies that offer free lunch?

This is how your code block should look (do read the comments for explanation):

 componentDidMount() {
      this.setTextInputValue();
      // call the below function from `setTextInputValue` as you have dependency on that
      // this.prepareTextBox();
  }

  setTextInputValue() {
    let textInputValues = [...this.state.textInputValues];
    this.state.samplearray.map((value) => {
       textInputValues = [ ...textInputValues , value] //default value

       // this is how you should call `prepareTextBox`
       // in setState callback as it will confirm that state is updated
       this.setState({ textInputValues },() => {
          this.prepareTextBox();
       })
    })
  }

  prepareTextBox() {
    let textInput = [...this.state.textInput];
    this.state.samplearray.map((value, index) => {
        textInput.push(<input value={this.state.textInputValues[index]}  key={index} />);
    })
    this.setState({ textInput })
  }
const { useState , useEffect } = React;

class App extends React.Component {
  
  constructor(props) {
      super(props);
      this.state = {
      textInputValues: [],
      textInput: [],
      samplearray:["Vivek","Darshita"]//gets an array from the JSON
      }
  }

  componentDidMount() {
      this.setTextInputValue();
  }

  setTextInputValue() {
    let textInputValues = [...this.state.textInputValues];
    this.state.samplearray.map((value) => {
       textInputValues = [ ...textInputValues , value] //default value
       this.setState({ textInputValues },() => {
          this.prepareTextBox();
       })
    })
  }

  prepareTextBox() {
    let textInput = [...this.state.textInput];
    this.state.samplearray.map((value, index) => {
        textInput.push(<input value={this.state.textInputValues[index]}  key={index} />);
    })
    this.setState({ textInput })
  }

  changeValues = () => {
    this.setState({
      textInput : [],
      textInputValues : ["New - Vivek" , "New - Darshita"]
    },() => {
      this.prepareTextBox();
    });
  }
  
  render() {
    return (
      <div>
        { this.state.textInput }
        <button onClick={this.changeValues}>Change Value</button>
      </div>
    );
  }
  
}

ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>
load more v
88%

User want to change his birthday. User click on TextField and see DatePicker Use select date with DatePicker I format this date and put inside TextField into value property.,Another option would be using defaultValue instead of value as TextField keeps updating it until it receives focus for the first time. And this will never happen while it's not editable.,Done with formatText prop and now input masking is supported. And for your question I can suggest the following:

  render() {
    const birthdayFormatted = TimeHelper.format(this.state.birthday, TimeHelper.PATTERN_MONTH_DAY_YEAR)
    return (
      <ClickableView onPress={() => this.setState({ showDatePicker: true })}>
        <Text>{birthdayFormatted}</Text> {/* in this line text rendered correctly*/}
        <TextField value={birthdayFormatted} editable={false} /> {/* in this line text render only initial value*/}
      </ClickableView>
    )
  }
load more v
72%

Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.,If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.,This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

import React, { useState } from 'react';
const Calculations = () => {

const [values,setValues]=useState({first:"",second:"",sum:""})
const [first,setFirst]=useState('')
const [second,setSecond]=useState('')
const [sum,setSum]=useState('')
const onChange=(e)=>{
    let name=e.target.name;
    let value=e.target.value;
    const newValues = {
    ...values,
    [name]: value
} 
setValues(newValues)
calcSum(newValues)
calcfirst(newValues)
calcSecond(newValues)


}
const calcSum = (newValues) => {
const { first,second} = newValues;
const newSum = parseInt(first,10)+parseInt(second,10)
setSum(newSum)
} 
const calcfirst = (newValues) => {
const { sum,second} = newValues;
const newFirst = parseInt(sum,10)-parseInt(second,10)
setFirst(newFirst)
} 
const calcSecond = (newValues) => {
const { sum,first} = newValues;
const newSecond = parseInt(sum,10)-parseInt(first,10)
setSecond(newSecond)
} 

return ( <form>
       <div style={{display:"flex",flexDirection:"column"}}>
        <label htmlFor="first">First</label>
        <input onChange={onChange} defaultValue={first} name='first' id="first" type="number"/>

        <label htmlFor="second">Second</label>
        <input onChange={onChange} defaultValue={second} name="second"  id="second" type="number"/>

        <label htmlFor="sum">Total</label>
        <input onChange={onChange} defaultValue={sum} id="sum" name="sum" type="number"/>


       </div>
    </form> );
}

export default Calculations;
load more v
65%

For example, let's say that as the user types, you're translating their words into a different language. In this new language, every single word is written the same way: 🍕. So the sentence "Hello there Bob" would be translated as "🍕🍕🍕".,In this example, we store text in the state, because it changes over time.,Text input is one of the ways the user interacts with the app. Next, let's look at another type of input and learn how to handle touches.

Pretag
 Pretag team - issue, fix, solve, resolve
75%

LinkedStateMixin is deprecated as of React v15. The recommendation is to explicitly set the value and change handler, instead of using LinkedStateMixin.,LinkedStateMixin is just a thin wrapper and convention around the onChange/setState() pattern. It doesn’t fundamentally change how data flows in your React application.,However, there are lots of applications that require you to read some data and flow it back into your program. For example, when developing forms, you’ll often want to update some React state when you receive user input. Or perhaps you want to perform layout in JavaScript and react to changes in some DOM element size.

import LinkedStateMixin from 'react-addons-linked-state-mixin'; // ES6
var LinkedStateMixin = require('react-addons-linked-state-mixin'); // ES5 with npm
load more v
40%

handleInputChange – This method can be used on change of the input fields. In this method we need to update the value based on the given index.,Create react application,Let’s start by creating a simple react application with the help of the create-react-app. If you don’t know how to create a react application then refer to the link below.

Pretag
 Pretag team - issue, fix, solve, resolve
22%

There's a lot to consider when working on a React application, especially when they involve forms. Even if you're able to create a submit button and update your app's state the way you want, clearing the forms can be difficult.,You've already handled storing the actual text in the state, so here's a simple way to clear the text from all input boxes.,In handleReset, you're able to set itemvalues back to a null state when the "Reset" button is pressed:

import React from "react";
import ReactDOM from "react-dom";
import Cart from "./Cart";

import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      Items: [
        {
          name: "item1",
          description: "item1",
          group: "groupA",
          dtype: "str"
        },
        {
          name: "item2",
          description: "item2",
          group: "groupA",
          dtype: "str"
        },
        {
          name: "item3",
          description: "item3",
          group: "groupB",
          dtype: "str"
        },
        {
          name: "item4",
          description: "item4",
          group: "groupB",
          dtype: "str"
        }
      ],
      itemvalues: [{}]
    };
    this.onChangeText = this.onChangeText.bind(this);
    this.handleReset = this.handleReset.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.findFieldIndex = this.findFieldIndex.bind(this);
    this.trimText = this.trimText.bind(this);
  }

  onChangeText = e => {
    const valuesCopy = [...this.state.itemvalues];
    //debugger;

    // get data-group value
    const itemvalue = e.target.dataset.group;

    if (!valuesCopy[0][itemvalue]) {
      valuesCopy[0][itemvalue] = [];
    }

    const itemvalues = valuesCopy[0][itemvalue];
    const index = this.findFieldIndex(itemvalues, e.target.name);

    if (index < 0) {
      valuesCopy[0][itemvalue] = [
        ...itemvalues,
        { [e.target.name]: e.target.value.split(",").map(this.trimText) }
      ];
    } else {
      // update the value
      valuesCopy[0][itemvalue][index][e.target.name] = e.target.value
        .split(",")
        .map(this.trimText);
    }

    // console.log(itemsCopy);

    this.setState({ itemvalues: valuesCopy });
  };
  findFieldIndex = (array, name) => {
    return array.findIndex(item => item[name] !== undefined);
  };
  trimText(str) {
    return str.trim();
  }

  handleReset = () => {
    this.setState({
      itemvalues: [{}]
    });
  };

  handleSubmit = () => {
    console.log(this.state.itemvalues);
  };

  render() {
    return (
      <Cart
        Items={this.state.Items}
        handleSubmit={this.handleSubmit}
        handleReset={this.handleReset}
        onChangeText={this.onChangeText}
      />
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
load more v
60%

It’s not uncommon to have a form that when an option is set other information is required from the user. This is where conditional fields come into play, and to support them let’s update our data structure a little bit:,With the data structure ready, it’s time to create the form. We’ll start with a new component called Form:,But in Amy’s case there were two more things that needed to be handled, let’s start with conditional fields.

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
load more v

Other "native-value" queries related to "React Native : Dynamically Created TextBox value is not getting updated"