Home > Mobile >  how to get value in dynamic text input in react.js?
how to get value in dynamic text input in react.js?

Time:04-04

I made one page in react.js project that has a text input and a button for each row of data. I want to get each input value by on click button and do process over it.

       {data.map((item, index) => <div><span>{item}</span>
                    <input type="text" placeholder='enter value' />
                    <button onClick={() => {alert(inputValue) }}>
                        click me
                    </button>

                </div>
                )}

CodePudding user response:

You can do something like this

const data = [0, 1, 2, 3];

export default function App() {
  const [inputs, setInputs] = useState({});

  return (
    <div className="App">
      {data.map((item) => (
        <div key={item}>
          <input
            onChange={(e) =>
              setInputs((prev) => {
                return { ...prev, [item]: e.target.value };
              })
            }
          />
          <button onClick={() => alert(inputs[item])}>Click</button>
        </div>
      ))}
    </div>
  );
}

Codesandbox: https://codesandbox.io/s/divine-wildflower-1ge7ev?file=/src/App.js:58-550

CodePudding user response:

The correct react way of doing this would be to create a standalone component e.g. UserInput and keep track of user input's state:

// Create state
const [input, setInput] = React.useState('')

return (
  <input type="text" placeholder='enter value'
    onChange={event => setInput(event.target.value)}
  />
  <button onClick={() => {alert(input) }}>
    click me
  </button>
);

You can then add this to your current component as follows:

{data.map((item, index) => <div><span>{item}</span><UserInput/></div>)}

CodePudding user response:

I suggest you use an object instead of an array. It's more appropriate for key-value pairs. If you use an object, it will be easier, readable and more maintainable.

How to do this?

You just need to modify your code to loop through the keys of your object then every time the input value changes (onChange), then set the value of the object onChange={(e) => data[key]=e.target.value}. To access the value when the button of the field is clicked, just use the data[key].

  • Related