Alok Alok - 1 month ago 14
React JSX Question

Populate input form field in a div on button click in React Js

I have to show the input text value that user enters in the input form field below the text box on a button click in reactjs.
I have created the function out of the render function and is returning the value and calling that function on button click but it is not working for me. I am not getting the value on button click which i am writing in textbox on the same page.
Whats the solution for this?

here i have created the function to set my nput state
here i have to return the state on button click in expression

Answer

Is this what you want?

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

    this.state = {
      values: {},
      showValues: {}
    }
  }

  handleChange(name, e){
    let values = this.state.values;
    values[name] = e.target.value;
    this.setState({values: values})
  }

  handleClick(e){
    let inputValues = this.state.values;
    this.setState({showValues: inputValues});
  }

  render(){
    return (
            <div>
                <input type="text" value={this.state.values["one"]} onChange={this.handleChange.bind(this, "one")}/>
                <p>{this.state.showValues["one"]}</p>
                <input type="text" value={this.state.values["two"]} onChange={this.handleChange.bind(this, "two")}/>
                <p>{this.state.showValues["two"]}</p>
                <input type="text" value={this.state.values["three"]} onChange={this.handleChange.bind(this, "three")}/>
                <p>{this.state.showValues["three"]}</p>
                <input type="text" value={this.state.values["four"]} onChange={this.handleChange.bind(this, "four")}/>
                <p>{this.state.showValues["four"]}</p>

                <button onClick={this.handleClick.bind(this)}>Show value</button>
           </div>
    )
  }
}

React.render(<Test />, document.getElementById('container'));

Here is updated jsfiddle.

Comments