Home > Software design >  Print from multiple text type inputs in React page
Print from multiple text type inputs in React page

Time:06-21

In this code I'm trying to get data from two inputs (names: x1 & x2) into two H1 tags inside the JSX, (Input1 & Input2).

But i get the same data inside the two H1 tags,In other words I want to assign x1 input -> Input1 & x2 input -> Input2, tried to find the solution online and in this forum, what am i missing here ?

Thanks !

import React from 'react';

class Winner extends React.Component {

constructor(props) {

    super(props);
    this.state = {
        Input1Value: 0,
        Input2Value: 0,
    }

}

state = {
    x1: '',
    x2: ''       
}

getValue = (event) => {
    this.setState({ x1: event.target.value});
    this.setState({ x2: event.target.value});
}

handleSubmit = () => {
    let value = this.state.x1;
    let value1 = this.state.x2;
    
    this.getResult(value,value1);
    
    
}

componentDidMount() {
    this.getResult("","");
}

getResult(value,value1) {
    
    let r = value;
    let x = value1;
                
    this.setState({
        Input1Value: r,
        Input2Value: x,        
        
    });
}
render() {
    return (
        <div>
            <h1>Winner</h1>
            <input type="text" name="x1" onChange={this.getValue} /> 
            <input type="text" name="x2" onChange={this.getValue} />       
          
            <button onClick={this.handleSubmit}>Click me!</button>
            <h1>Input1: {this.state.Input1Value}</h1>
            <h1>Input2: {this.state.Input2Value}</h1>               
        </div>
    )
}
}
export default Winner;

CodePudding user response:

You can change the getValue function like this;

getValue = (event) => {
    const value = event.target.value;
    this.setState({
    ...this.state,
    [event.target.name]: value
  });
}

By doing it this way, no matter how many input fields you use, you can keep any input as long as their names are different. If you define a second state as you mentioned in the comment, a different state will be required for each input.

  • Related