RogerFedFan
RogerFedFan

Reputation: 566

React - Update Value Of Input After Submit

I'm trying to make a feature where a user can edit a submitted value. So to be completely clear:

  1. You would enter some text
  2. Click submit and that value will be pushed into an array
  3. You will be able to see your value on the dom
  4. If you made an error, you can click on that input and change the value, also updating the state of that value in the already pushed array.
  5. On a button click, you will update the state and have a newly edited value.

I'm stuck on the part of changing the state of the value of the pushed items in the array.

For example:

If I were to click on the field of 'Bob', edit it and click submit, the value of whatever I changed it to would also change the state of what was originally in my array to the new value.

This is what I have so far:

import React, { Component } from 'react'

export default class App extends Component {
  constructor(props) {
    super(props)

    this.state = {
      notes: ['hello', 'bob'],
      val: ''
    }
  }

  submit = () => {
    const { notes, val } = this.state

    notes.push(val)
    this.setState({notes})
  }

  handleEdit = e => {
    console.log(e)
  }

  render() {
    return (
      <div>
        <input 
          type="text" 
          onChange={e => this.setState({val: e.target.value})}
        />

        <button onClick={this.submit}>Submit</button>

        {this.state.notes.map(item => {
          return (
           <form onSubmit={e => e.preventDefault()}>
             <input 
               type="text" 
               defaultValue={item}
               onChange={e => this.setState({val: e.target.value})}
             />
             <button onClick={() => this.handleEdit(item)}>Submit 
Change</button>
           </form>
          )
        })}
      </div>
    )
  }
}

Upvotes: 2

Views: 3455

Answers (1)

Deepak
Deepak

Reputation: 870

Try this kind of thing :

handleEdit = (item) => {
  const notes = this.state.notes.slice();
  const index = notes.indexOf(item);
  notes[index] = this.state.val;
  this.setState({
    notes
  })
}

Upvotes: 1

Related Questions