React App - removing dynamically-created TextInput always removes the last in the array

Asked
Active3 hr before
Viewed126 times

8 Answers

react
90%

As per your code, there is no issue, it should work perfectly fine, ,I think due to same name or kind of that you are misunderstanding like its removing always last :, What is the name of this town in Italy?

const { useState , useEffect } = React;

class App extends React.Component {
  
  state = {
    certification : ["Cert 1","Cert 2","Cert 3","Cert 4","Cert 5","Cert 6","Cert 7","Cert 8"]
  }
  
  removeCertClick = (i) => {
    let certification = [...this.state.certification];
    certification.splice(i,1)
    this.setState({certification})
  }


  render() {
    return (
      <div>
        With Name :
        <br/><br/>
        {
          this.state.certification.map((crt,i) => <button onClick={() => this.removeCertClick(i)}>{crt} - X</button>)
        }
        <br/><br/>
        Button Name With Index : (Looks like you are removeing last always) :
        <br/><br/>
        {
          this.state.certification.map((crt,i) => <button onClick={() => this.removeCertClick(i)}>Remove {i}</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%

Today we will show you how to add or remove input fields dynamically with ReactJS. In a real project, sometimes you need to implement the dynamic form fields using React. So you will find the step by step instruction to create dynamic form.,Check out your requested article: Set focus on the dynamic input field in React,You can use the dropdown element the same as an input field. The following link will help you to implement dropdown.

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

Now, in the </Item> component, we can accept the data carried by the props object and use it to initialize the state of the <Item/> component! ,Now, since we have passed a reference via props, we can access the reference to that function in <Item/> like so. item.jsx,The component that owns the state, should be the one modifying it.

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

I have used arrays to generate TextInput component as well as to retrieve data from each TextInput. Following is the output of the react native example.,In this blog post, I am going to write about how to dynamically add or remove Text Input component and get corresponding values from each text input in react native.,How to Use Set Timeout in React Native

Here’s the complete code of the react native example:

import React, { Component } from 'react';
import { View, TextInput, Button, StyleSheet } from 'react-native';


class MyClass extends Component {

  constructor(props){
    super(props);
    this.state = {
      textInput : [],
      inputData : []
    }
  }

  //function to add TextInput dynamically
  addTextInput = (index) => {
    let textInput = this.state.textInput;
    textInput.push(<TextInput style={styles.textInput}
      onChangeText={(text) => this.addValues(text, index)} />);
    this.setState({ textInput });
  }

  //function to remove TextInput dynamically
  removeTextInput = () => {
    let textInput = this.state.textInput;
    let inputData = this.state.inputData;
    textInput.pop();
    inputData.pop();
    this.setState({ textInput,inputData });
  }

  //function to add text from TextInputs into single array
  addValues = (text, index) => {
    let dataArray = this.state.inputData;
    let checkBool = false;
    if (dataArray.length !== 0){
      dataArray.forEach(element => {
        if (element.index === index ){
          element.text = text;
          checkBool = true;
        }
      });
    }
    if (checkBool){
    this.setState({
      inputData: dataArray
    });
  }
  else {
    dataArray.push({'text':text,'index':index});
    this.setState({
      inputData: dataArray
    });
  }
  }

  //function to console the output
  getValues = () => {
    console.log('Data',this.state.inputData);
  }


  render(){
    return(
      <View>
        <View style= {styles.row}>
          <View style={{margin: 10}}>
        <Button title='Add' onPress={() => this.addTextInput(this.state.textInput.length)} />
        </View>
        <View style={{margin: 10}}>
        <Button title='Remove' onPress={() => this.removeTextInput()} />
        </View>
        </View>
        {this.state.textInput.map((value) => {
          return value
        })}
        <Button title='Get Values' onPress={() => this.getValues()} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  buttonView: {
  flexDirection: 'row'
  },
  textInput: {
  height: 40,
  borderColor: 'black', 
  borderWidth: 1,
  margin: 20
},
row:{
  flexDirection: 'row',
  justifyContent: 'center'
  },
});

export default MyClass;
75%

Using this, we first create a ref to an element in the JSX of a component class:,Indicate the human language of page texts as screen reader software uses this to select the correct voice settings:,To set focus in React, we can use Refs to DOM elements.

<input
  type="text"
  aria-label={labelText}  aria-required="true"  onChange={onchangeHandler}
  value={inputValue}
  name="name"
/>
load more v
40%

Adding a field works fine, however, the remove always removes the last field, not the one which I wanted to remove.,You can see that the above step removes the 2nd field, not the 1st field.,I'm trying to create a form where I'm letting user to add as many number of input fields and also giving an ability to remove any particular added input field.

function App() {
  const [fields, setFields] = useState([{ value: null }]);

  function handleChange(i, event) {
    const values = [...fields];
    values[i].value = event.target.value;
    setFields(values);
  }

  function handleAdd() {
    const values = [...fields];
    values.push({ value: null });
    setFields(values);
  }

  function handleRemove(i) {
    const values = [...fields];
    values.splice(i, 1);
    setFields(values);
  }

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>

      <button type="button" onClick={() => handleAdd()}>
        +
      </button>

      {fields.map((field, idx) => {
        return (
          <div key={`${field}-${idx}`}>
            <input
              type="text"
              placeholder="Enter text"
              onChange={e => handleChange(idx, e)}
            />
            <button type="button" onClick={() => handleRemove(idx)}>
              X
            </button>
          </div>
        );
      })}
    </div>
  );
}
22%

Tip: The props of your Input components are passed to a react-final-form Field component.,That means that if you want to create a link to a creation form, presetting some values, all you have to do is to set the location state. react-router-dom provides the <Link> component for that:,Sometimes, you may want to alter the form values before sending them to the dataProvider. For those cases, use the transform prop either on the view component (<Create> or <Edit>) or on the <SaveButton> component.

<Resource name="posts" create={PostCreate} edit={PostEdit} />
                               ----------        --------
                                    |               |
    displayed when browsing to /posts/create        |
                                                    |
                    displayed when browsing to /posts/123
load more v
60%

Once you have done this, let's add the JavaScript that rounds out our starting page. Within the same src directory, add a new file called index.js. Inside this file, add the following content:,Individually, all of these little implementation details are easy to wrap our brain around. When we put them together, there are a few things to watch out for. We will look at all that and more in the following sections.,Now that we've done this, it is time to create our addItem event handler that will get called when our form gets submitted. Add the following highlighted lines just above where we have our render function defined:

Pretag
 Pretag team - issue, fix, solve, resolve

Other "react-undefined" queries related to "React App - removing dynamically-created TextInput always removes the last in the array"