Home > database >  React input element value edit field
React input element value edit field

Time:06-12

// data.js
export default [5, 2, 7, 9]
import data from './data.js'

const [number, setNumber] = useState(null)

function Test() {
    return (
        {
            data.map((item, index) => {
                return (
                    <input 
                        key={index} 
                        value={item}
                    />    
                )   
            })        
        }
    )
}

https://codesandbox.io/s/input-3q22e2?file=/src/App.js

My input element has default value from props.

I use list array to show it.

How can I edit input that input filed after first render.

I don't know how to bind attribute value to another state

CodePudding user response:

You need to add onChange method to edit the value.

import React, {useState} from 'react';

const list = [5, 2, 7, 9]
const [values, setValues] = useState(list);

function Test() {
    return (
        {
            list.map((item, index) => {
                return (
                    <input 
                        key={index} 
                        value={values[index]}
                        onChange={e=>setValues({
                           ...values,
                           index:e.target.value
                        })}
                    />    
                )   
            })        
        }
    )
}

CodePudding user response:

I'm rather new to React, so I'm sure there is another way. Hopefully someone comes along with a better implementation.

The first answer was kind of on the right track. To update your array you can do the following.

function App() {
    const [number, setNumber] = useState(null);

    const onChangeHandler = (event, index) => {
        setNumber(data[index] = Number(event.target.value));
    }

    return (
        <div className="App">
            <h1>Hello CodeSandbox</h1>
            {data.map((item, index) => {
                return <input key={item[index]} value={item} onChange={e => onChangeHandler(e, index)} />
            })}
        </div>
    )
}
  • Related