Place the values of two inputs inside an array in React?

Asked

Viewed 138 times

0

How do I take the values of two inputs and place inside an array with the event onChange?

For example:

input1 = 10;
input2 = 20;

notas = [10, 20];

Follows the code:

import React, { Component } from "react";

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

    this.state = {
      text: "",
      notas: [],
    };
  }

  input = (e) => {
    
    this.setState({
      [e.target.name]: e.target.value,
    }, () => {
      const array = [this.state.text]
      this.setState({
        notas: array
      }, () => {
        console.log(this.state.notas);
      });
    });
  };

  render() {
    return (
      <div>
        <label>Nota 1</label>
        <input type="text" name="text" onChange={this.input} /> <br /> <br/>

        <label>Nota 2</label>
        <input type="text" name="text" onChange={this.input} /> <br /> <br/>
        
      </div>
    );
  }
}
  • Could someone help me ?

1 answer

1


The first point is that you need some way to distinguish the two <input>s you are using, so as to insert them in the correct positions of the array.

Once you’ve done that, just position them in the array according to the identification. Something like:

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      notas: [0, 0]
    };
  }

  input = (e) => {
    // Mapeia cada nome para a posição (índice) do array:
    const nameToIndexMap = {
      'nota-1': 0,
      'nota-2': 1
    };
    
    const name = e.target.name;
    const val = parseInt(e.target.value || 0, 10);
    
    this.setState((prevState) => {
      // Copiamos o array:
      const copy = [...prevState.notas];
      // Modificamos o índice de acordo com o nosso mapa:
      copy[nameToIndexMap[name]] = val;
      
      return { ...prevState, notas: copy };
    });
  };

  render() {
    return (
      <div>
        <label>Nota 1</label>
        <input type="text" name="text" name="nota-1" onChange={this.input} />
        
        <br />

        <label>Nota 2</label>
        <input type="text" name="text" name="nota-2" onChange={this.input} />
        
        <pre>{JSON.stringify(this.state.notas, null, 2)}</pre>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.querySelector('#root'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Simplify a bit using the new React Hooks API. :)

  • Thanks Luiz, helped me a lot, thanks really. Just a doubt, the prevState has what function, I did not know him yet.

  • @daniel, the setState can also accept a callback (as I did in my reply). In this case, it receives as parameter the value of the status before the update is made. See API of React to learn more. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.